kotlin 使用viewStub

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a243920187/article/details/82352286

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;

猜你喜欢

转载自blog.csdn.net/a243920187/article/details/82352286
今日推荐