您的位置:首页 > 产品设计 > UI/UE

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

2012-01-05 21:31 603 查看
首先看下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>

效果截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息