0

Is it possible to inflate a ViewStub with a native android widget?

For example:

<LinearLayout...>
 <TextView...>
 <TextView...>
 <ViewStub...>
</LinearLayout>

I want to replace/inflate the ViewStub with a Switch or a Checkbox. Is that possible?

Vas
  • 2,014
  • 3
  • 22
  • 38
  • Have you read here? https://stackoverflow.com/a/37442268/2910520, what you need is the same thing – MatPag Jun 12 '17 at 21:48
  • Yes I did. It's not quite the same thing as the layout I'm trying to inflate is for a native android widget. I don't have an explicit layout for it. – Vas Jun 12 '17 at 21:56
  • You should create a new layout representing the thing you want to inflate. Currently there is no way to inflate a View object in a StubView – MatPag Jun 12 '17 at 22:14

2 Answers2

0

To set the layout to inflate into the ViewStub either:

Set the layout via XML:

<ViewStub 
   android:id="@+id/stub"
   android:inflatedId="@+id/myLayout"
   android:layout="@layout/myLayout"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" />

Or, set the layout at runtime:

viewStub.setLayoutResource(R.layout.myLayout);

Then, you can inflate the ViewStub.

View inflatedView = viewStub.inflate();

You could call this inflate() method from where you want, such as a Switch or Checkbox being clicked (as you asked).

  • So what layout resource should it be set to if I want to inflate a native android switch widget? – Vas Jun 12 '17 at 21:57
  • You create a layout file that contains a Switch widget. Then inflate that layout resource. –  Jun 23 '17 at 14:04
0

Currently there is no way to replace the StubView with a View object. You must create a layout representing the view you want to replace. So for example, if you want to switch it with a single CheckBox, you need to create a layout like this

<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_checkbox"
    android:text="Click me"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Then calling

viewStub.setLayoutResource(R.layout.my_checkbox);
viewStub.inflate();

If you need a reference to the inflated view you can use this instead

CheckBox checkInflated = (CheckBox)viewStub.inflate();
MatPag
  • 41,742
  • 14
  • 105
  • 114