kotlin 使用viewStub

ViewStub是一个轻量级的的View,继承于ViewGroup,没有任何尺寸,不绘制任何东西,因此绘制或者移除时更省时。(ViewStub不可见,大小为0)

优点

实现View的延迟加载,避免资源的浪费,减少渲染时间,在需要的时候才加载View

缺点

  • ViewStub所要替代的layout文件中不能有标签
  • ViewStub在加载完后会被移除,或者说是被加载进来的layout替换掉了

用法

<ViewStub
    android:id="@+id/stub_id"
    android:layout="@layout/view_stub_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

view_stub_layout.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/index_page_bg"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_advert_hot_expert"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:background="@color/white"
        android:gravity="center"
        android:text="预留广告位置" />

</LinearLayout>

用ViewStub加载layout文件时,可以调用 setVisibility(View.VISIBLE)或者inflate()

  • stub_id.inflate() 或者
  • stub_id.visibility = View.VISIBLE

注意

  • 一旦ViewStub visible/inflated,则ViewStub将从视图框架中移除,其id stub_import也会失效
  • ViewStub被绘制完成的layout文件取代,并且该layout文件的root view的id是android:inflatedId指定的id panel_import,root view的布局和ViewStub视图的布局保持一致

所以,当inflate()之后,需要这样写:

tv_advert_hot_expert!!.text = "我是viewstub里的view"

stub_id已经失效,如果再使用这个id,会报nullpointException;

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值