本文将就ViewStub的优缺点及使用方法展开分析。如有错误欢迎批评指正,共同交流,共同进步。如果本篇文章对你有一点帮助,欢迎点赞。
一、ViewStup是什么?
ViewStup是一个轻量级的view,之所以说它是轻量级的view是因为它在页面加载渲染的过程中不会去绘制,只是在你需要的时候再去绘制。
二、viewStup的使用场景
只有在特定条件下才展示的布局,初始化时默认不需要加载的布局等
三、viewStup的优缺点
优点:占用内存少,页面渲染速度快,避免资源浪费
缺点:不能使用</merge>标签
四、viewStup的使用
viewStup在使用上类似于include标签,只是在引用layout的时候使用,下面我们来看一个简单的实例来加深理解:
public class MainActivity extends AppCompatActivity {
private Button btn;
private ViewStub viewStub;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
viewStub = (ViewStub) findViewById(R.id.view_stub);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
viewStub.inflate();
}
});
}
}
这是activity_main的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点我"/>
<ViewStub
android:id="@+id/view_stub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout="@layout/viewstub_view"/>
</LinearLayout>
这是viewstub_view的代码:
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="需要我时我才显示,么么哒!!" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="需要我时我才显示,么么哒!!" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="需要我时我才显示,么么哒!!" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="需要我时我才显示,么么哒!!" />
</LinearLayout>
运行程序,页面上只有一个button显示,
点击按钮后,执行inflate();方法后
看到这不要关掉页面,继续往下看!!!!
注意:
1.viewStub不能使用merge标签(merge标签用法请看点击打开链接)
2.viewStub在不能连续调用inflate();会报错,因为一旦inflate()后,viewStub的位置就被占用了,再次调用就会报错