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

      首先看下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>
  
 

效果截图:

  

    

   

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值