ViewStub使用

在开发应用程序的时候,经常会遇到这样的情况,会在运行时动态根据条件来决定显示哪个View或者某个布局。
那么最通常的想法就是把可能用到的View的可见性都设为View.GONE,然后在代码中改变他的可见性。这样做的
优点是逻辑简单而且控制起来比较灵活。但是他的缺点是,耗费资源。虽然把View的初始可见View.GONE但是在
inflate布局的时候View仍然会被Inflate,也就是说仍然会创建对象,会被实例化,会被设置属性。
推荐的做法是使用Android.view.ViewStub,ViewStub是一个轻量级的View,它是一个看不见的,不占布局位置,
占用资源非常小的控件。可以为ViewStub指定一个布局,在inflate布局的时候,只有ViewStub会被初始化,然
后当ViewStub被设置为可见的时候,或是调用了ViewStub.inflate()的时候,ViewStub所向的布局就会被
inflate和实例化,然后ViewStub的布局属性都会传给它所指向的布局。这样,就可以使用ViewStub来方便的在
运行时,要还是不要显示某个布局。

ViewStub的一些特点
1.ViewStub只能inflate一次,之后ViewStub对象会被置为空。换句话说,某个被ViewStub指定的布局被inflate
后,就不会在通过ViewStub来控制它了。
2.ViewStub只能用来inflate一个布局文件,而不是某个具体的View
因为设置给ViewStub的只能是某个布局文件的id,所以无法让他来控制某个View。
所以如果想要控制某个View的显示与隐藏,或者想要在运行时不断显示与隐藏某个布局或View,只能使用V我的
可见性来控制。
3.某些布局属性要加在ViewStub而不是实际的布局上面,才会起作用,比如上面的android:layout_margin系列
属性,如果加在View上则不会其作用,需要放在它的ViewStub上面才会起作用。而ViewStub的属性在inflate后

会都传给相应的布局。

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout  
  xmlns:android="http://schemas.android.com/apk/res/android"  
  android:orientation="vertical"  
  android:layout_width="fill_parent"  
  android:layout_height="fill_parent"  
  android:gravity="center_horizontal">  
  <ViewStub   
    android:id="@+id/viewstub_demo_text"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_marginLeft="5dip"  
    android:layout_marginRight="5dip"  
    android:layout_marginTop="10dip"  
    android:layout="@layout/viewstub_demo_text_layout"/>  
  <ViewStub   
    android:id="@+id/viewstub_demo_image"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_marginLeft="5dip"  
    android:layout_marginRight="5dip"  
    android:layout="@layout/viewstub_demo_image_layout"/>  
</LinearLayout>  


<?xml version="1.0" encoding="utf-8"?>  
<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>  


代码中进行inflate进行显示

 ViewStub stub = (ViewStub) findViewById(R.id.viewstub_demo_text);  
 stub.inflate();  




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值