Android优化篇 ViewStub按需加载布局

作者: TryEnough | 来源:发表于2019-01-26 17:37 被阅读5次

原文链接

更多教程


你将学到

1.ViewStub标签的使用姿势
2.ViewStub标签的使用例子
3.ViewStub标签的使用注意点

ViewStub标签的使用姿势

  • 步骤一:定义需要懒加载的布局 test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#36e7ea"
        android:gravity="center"
        android:textSize="18sp" />
        
</LinearLayout>
  • 步骤二:使用ViewStub引入要懒加载的布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

    <Button            //点击按钮时才加载下面的ViewStub布局
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加载ViewStub" />

    <ViewStub  //这个布局现在还不会被添加到布局树中
        android:id="@+id/view_stub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout="@layout/test" />  //这里指定要加载的布局名字
        
</LinearLayout>
  • 步骤三:使用代码按需加载上面的ViewStub布局
    这里是点击按钮的时候添加:
Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            View view = ((ViewStub)findViewById(R.id.view_stub)).inflate();  //加载出来用view接收
            TextView tv = (TextView) view.findViewById(R.id.text_view); //然后可以用view访问它的子控件
            tv.setText("ViewStub的使用");
    }
});

效果:
点击按钮前:



点击按钮后,出现了需要临时加载的布局:


ViewStub使用注意点

  • ViewStub对象只可以Inflate一次,之后ViewStub对象会被置为空。
    所以,inflate一个ViewStub对象之后,就不能再inflate它了,否则会报错:ViewStub must have a non-null ViewGroup viewParent。。
  • ViewStub不支持merge标签,意味着你不能引入包含merge标签的布局到ViewStub中。
    否则会报错:android.view.InflateException: Binary XML file line #1: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true

原文链接

更多教程

相关文章

网友评论

    本文标题:Android优化篇 ViewStub按需加载布局

    本文链接:https://www.haomeiwen.com/subject/mfvijqtx.html