0

是否可以使用原生 android 小部件为 ViewStub 充气?

例如:

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

我想用 Switch 或 Checkbox 替换/膨胀 ViewStub。那可能吗?

4

2 回答 2

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();
于 2017-06-12T22:20:00.030 回答
0

要将布局设置为膨胀为ViewStub

通过 XML 设置布局:

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

或者,在运行时设置布局:

viewStub.setLayoutResource(R.layout.myLayout);

然后,您可以为ViewStub.

View inflatedView = viewStub.inflate();

您可以从您想要的位置调用此inflate()方法,例如 aSwitch或被Checkbox单击(如您所问)。

于 2017-06-12T21:50:45.357 回答