Android之ViewStub

Android之ViewStub

前言

当渲染一个活动时,这个活动的布局可能会有很多visible为invisible和gone的情况,虽然这些控件虽然现在不显示在屏幕上,但是系统在加载这个布局文件时还是会加载它的,这就影响了这个页面的加载效率,因为这些不可见的控件提前加载它们并没有什么实际的意义,反而会减缓页面的加载时间,所以为了解决这个问题可以使用ViewStub来懒加载暂时不显示的布局.

1.ViewStub的优势

简单来说, ViewStub可以做到按需加载一个布局,我们可以控制它加载的时机,而不是在Activity的onCreate方法中去加载.即懒加载

2.ViewStub的使用

    <ViewStub
        android:id="@+id/stub"
        android:inflatedId="@+id/text"
        android:layout="@layout/text_view_stub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/textView3"
        android:layout_marginTop="180dp"
        android:layout_marginLeft="100dp"/>
属性功能
android:inflatedId="@+id/text"为我们要加载的布局提供一个id
android:layout我们需要加载的布局

除此之外

        app:layout_constraintTop_toBottomOf="@id/textView3"
        android:layout_marginTop="180dp"
        android:layout_marginLeft="100dp"/>

这些代表我们懒加载的布局在父布局的位置,如果懒加载的布局有相同的属性,将会被覆盖

//通过id得到viewStub对象
ViewStub viewStub = findViewById(R.id.stub);
//动态加载布局
 viewStub.inflate();

3.注意事项

inflate方法只能调用一次,再次调用会出异常
我们看下inflate方法的源码,一旦第二次调用inflate方法,我们的到viewParent将等于null,会报 throw new IllegalStateException(“ViewStub must have a non-null ViewGroup viewParent”);异常,所以总之一句话,这个懒加载只能加载一次

public View inflate() {
       final ViewParent viewParent = getParent();

       if (viewParent != null && viewParent instanceof ViewGroup) {
           if (mLayoutResource != 0) {
               final ViewGroup parent = (ViewGroup) viewParent;
               final View view = inflateViewNoAdd(parent);
               replaceSelfWithView(view, parent);

               mInflatedViewRef = new WeakReference<>(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");
       }
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值