Android 使用ViewStub优化布局

1、简介

  • 定义:ViewStub是View的子类,它不可见,大小为0,用来延迟加载布局资源

    • 当ViewStub被设置成可见(Visible),或者它的 inflate() 方法被调用的时候,布局资源才会被填充,然后ViewStub本身就会被填充起来的布局资源替换掉
  • 与Visbility.GONE的区别

    属性特征
    ViewStub把View设置成GONE,但是ViewTree仍旧被inflate 生成对象占用资源。只是避过了Layout、measure、draw的环节。
    Visbility.GONEViewStub在没有inflate时只是 空白的View,不消耗资源

2、使用

  • 常用属性:

    属性特征
    android:id指定ViewStub ID,用于查找ViewStub进行延迟加载
    android:layout延迟加载布局的资源id
    android:inflatedIdViewStub的父窗体的id,用于加载layout指定的控件
  • 在xml中设置控件

    <ViewStub 
        android:id="@+id/stub"
        android:inflatedId="@+id/subTree"
        android:layout="@layout/mySubTree"
        android:layout_width="120dip"
        android:layout_height="40dip" />
    
  • 在Java中加载布局

    ViewStub stub = (ViewStub) findViewById(R.id.stub);
    View inflated = stub.inflate();
    
    • stub调用inflate()方法后,子布局被返回(即赋值给本例中的inflated)
  • tips

    • inflate() 方法只能调用一次,多次调用可以使用 try catch + setVisbility() 实现
      try {
          View iv_vsContent = viewStub.inflate();     //inflate 方法只能被调用一次,
          hintText = (TextView) iv_vsContent.findViewById(R.id.tv_vsContent);
      } catch (Exception e) {
          viewStub.setVisibility(View.VISIBLE);
      } finally {
          hintText.setText("没有相关数据,请刷新");
      }
      
    • ViewStub所指向的替换它的布局必须单独另外写一个layout文件(且该布局文件必须要有一个父布局,不能直接放控件)
      eg:R.layout.iv_vsContent;
      
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
          <ImageView
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="0dp"
              android:layout_weight="1"
              android:src="@mipmap/ic_launcher"/>
      
          <TextView
              android:id="@+id/tv_vsContent"
              android:layout_width="match_parent"
              android:layout_height="@dimen/dp30"/>
      </LinearLayout>
      

3、inflate源码及setVisbility源码解析

  • (1)ViewStub中的inflate方法

    • inflate只能使用一次的原因:
      当ViewStub 调用inflate() 将其引用的 布局/view 展示出来之后,ViewStub本身就会从视图树中被移除,此时viewStub 就获取不到他的 父布局
//源码
public View inflate() {
    final ViewParent viewParent = getParent();

    if (viewParent != null && viewParent instanceof ViewGroup) {
        if (mLayoutResource != 0) {
            final ViewGroup parent = (ViewGroup) viewParent;
            final LayoutInflater factory;
            if (mInflater != null) {
                factory = mInflater;
            } else {
                factory = LayoutInflater.from(mContext);
            }
            final View view = factory.inflate(mLayoutResource, parent,
                    false);

            if (mInflatedId != NO_ID) {
                view.setId(mInflatedId);
            }
            
            //移除ViewStub
            final int index = parent.indexOfChild(this);
            parent.removeViewInLayout(this);

            //获取ViewStub的参数
            final ViewGroup.LayoutParams layoutParams = getLayoutParams();
            if (layoutParams != null) {
                parent.addView(view, index, layoutParams);
            } else {
                parent.addView(view, index);
            }

            mInflatedViewRef = new WeakReference<View>(view);

            if (mInflateListener != null) {
                mInflateListener.onInflate(this, view);
            }

            return view;
        } else {
            throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
        }
    } else {
        throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
    }
}
  • (2)ViewStub中的setVisibility()

    • setVisibility会调用inflate,但却可以使用多次
    • ViewStub 的setVisibility() 方法中,会先判断 WeakReference 类型的成员变量 mInflatedViewRef 是否为空。第一次调用setVisibility()的时候,mInflatedViewRef并没有初始化,也就是说是null,那么这时候就会走inflate()。
    • 在inflate() 方法中给被填充起来的布局/view创建一个WeakReference弱引用,并赋值给mInflatedViewRef,从而完成mInflatedViewRef的初始化。
    • 当第二次走setVisibility() 的时候,mInflatedViewRef已经不再是null,就会调用 WeakReference 的父类Reference 中的get() 方法获取该引用指向的实体对象,也就是说通过get() 拿到 被填充的view对象,然后再走View类的setVisibility()。
// 源码
public void setVisibility(int visibility) {
    if (mInflatedViewRef != null) {
        View view = mInflatedViewRef.get();
        if (view != null) {
            view.setVisibility(visibility);
        } else {
            throw new IllegalStateException("setVisibility called on un-referenced view");
        }
    } else {
        super.setVisibility(visibility);
        if (visibility == VISIBLE || visibility == INVISIBLE) {
            inflate();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值