前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >kotlin 使用viewStub

kotlin 使用viewStub

作者头像
全栈程序员站长
发布2022-09-13 14:43:32
5110
发布2022-09-13 14:43:32
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

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;

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/153986.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 优点
  • 缺点
  • 用法
  • 注意
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档