Android中使用ViewStub来提高UI的加载的性能

本文详细介绍了如何使用ViewStub在Android应用中动态添加视图,提高性能,并提供了完整的示例代码及运行效果截图。通过在布局文件中定义ViewStub节点,在Activity中通过inflate()方法将其视图添加到界面中,避免了在onCreate()方法中加载布局,实现了视图的动态加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先看下API中的ViewStub

根据的文档的说明,ViewStub是一种默认不可见的试图,它没有大小,所以不能被改变,也不能通过某些把viewstub添加到布局当中来,

不过我们可以使用inflate()来吧ViewStub中的试图增加进行,这样可以实现动态的添加试图,不必要每次在onCreate()的时候就加载布局,可以提高我们的性能。

Demo中的使用方法:

1:新建布局文件 设置<ViewStub>节点

2: 在Activity中进行按钮点击 viewStub = (ViewStub) findViewById(R.id.mystub);

3:View view = viewStub.inflate(); 把ViewStub中的View增添进来

下面Demo源代码:

主Activity类:

package com.jiangqq.viewstubdemo; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewStub; import android.widget.Button; public class ViewStubActivity extends Activity { private Button btn; private ViewStub viewStub; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { viewStub = (ViewStub) findViewById(R.id.mystub); View view = viewStub.inflate(); v.setEnabled(false); } }); } }

布局文件:

main.xml:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击确定" /> <ViewStub android:id="@+id/mystub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout="@layout/demo_viewstub" > </ViewStub> </LinearLayout> demo_viewstub.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ViewStubDemo_Byjiangqq" /> </LinearLayout>

效果截图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值