关于ViewStub的使用方法网络上有很多,但是某些细节不注意的话,运行时就会出现不可预知的错误。
1.引用布局文件的属性为android:layout,而不是layout(与incluce的区别)
2.除了android:id属性,还有一个与id有关的属性inflateId
一个ViewStub的例子:
<ViewStub
android:id="@+id/pic_stub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:inflatedId="@+id/pic_view_id_after_inflate"
android:layout="@layout/pic_view" />
pic_view代码
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/viewstub_demo_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#aa664411"
android:textSize="16sp"/>
</LinearLayout>
网络上很多例子是这么写的:
ViewStub stub = (ViewStub) findViewById(R.id.pic_stub);
stub.inflate();
TextView text = (TextView) findViewById(R.id.viewstub_demo_textview);
实际上这么写后续在使用时,会报text的空指针。
最后查看官方文档得到正确的写法应是:
ViewStub stub = (ViewStub) findViewById(R.id.pic_stub);
stub.inflate();
//ViewStub调用inflate()方法后,ViewStub被替换为以inflateId为Id的视图。网络上很多博客都提到了这句话,但在代码示例中并没有如下这句。实际运行中导致使用text时报空指针错误。
View view=findViewById(pic_view_id_after_inflate);
TextView text = (TextView) view.findViewById(R.id.viewstub_demo_textview);
参考文献:http://blog.csdn.net/jason0539/article/details/26132267