ViewStub的使用

来源:互联网 发布:德国网络加速器 编辑:程序博客网 时间:2024/06/06 03:43
  • 我们在开发的时候经常会遇到一些情况:一些布局事先不确定要不要显示出来,等到运行的时候才能决定是要不要显示出来或者是要哪些布局显示出来。我们一般会将其visibility属性设置为gone, 等运行的时候再设置为visibble。不要以为设置为gone,在加载布局的时候就不会加载出来,它一样会实例化的,这样就并没有起到一个优化的作用。
  • Android有一个比较适合这种情况的控件——ViewStub, 可以将布局写到另一个xml的layout中,然后用ViewStub来引入,比如在一个Activity中,第一次打开的时候并不会将布局显示出来,也不会对其进行任何的实例化,更不会加载,当调用viewStub的inflate方法的时候,布局会被实例化、加载、并渲染。
  • 缺点:它只能被inflate一次,不可以进行重复的显示与隐藏操作,如果要多次操作显示与隐藏,那还是设置visibility属性为好。
  • 下面贴出一些代码:
    • activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout 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:id="@+id/content_main"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ViewStub        android:id="@+id/stub_view1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout="@layout/layout_stub"/></RelativeLayout>
- layout_stub.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <Button        android:id="@+id/btn1"        android:layout_width="match_parent"        android:layout_height="50dp"        android:text="ViewStub测试"/>    <Button        android:id="@+id/btn2"        android:layout_width="match_parent"        android:layout_height="50dp"        android:text="ViewStub测试"/>    <Button        android:id="@+id/btn3"        android:layout_width="match_parent"        android:layout_height="50dp"        android:text="ViewStub测试"/>    <Button        android:layout_width="match_parent"        android:layout_height="50dp"        android:text="ViewStub测试"/></LinearLayout>
- MainActivity中的关键代码
viewStub = (ViewStub) findViewById(R.id.stub_view1);viewStub.inflate();
  • 测试:我测试比较了一下,用加载了8个Button,用ViewSub与不用ViewStub不同情况下显示内存的占用量是0.8MB,
  • 不用ViewStub
    • 这里写图片描述
  • 用ViewStub
    • 这里写图片描述

-结果:对于不用重复显示的情况,用ViewSub还是比较优化的。

0 0
原创粉丝点击