您的位置:首页 > 移动开发 > Android开发

android开发布局优化之ViewStub

2015-07-29 20:35 513 查看
使用ViewStub可以延迟加载一个布局文件,提高显示速率。刚开始接触到,记录下来。

关于viewstub的使用,我们可以在不同的布局中使用,比如可以根据设备的大小动态决定显示哪个界面。

viewstub和include比较像,都是在一个布局文件中嵌入另外一个布局文件,然而viewstub是可以说是延迟加载,它只会在你手动指定加载的时候才会加载这个布局文件,而include则会立即加载。

在布局中使用ViewStub标签来引入文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.viewstub.MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

<Button
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="显示/隐藏" />

<ViewStub
android:id="@+id/vs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inflatedId="@+id/inflated_id"
android:layout="@layout/view_stub_layout" />

</LinearLayout>


view_stub_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="vs中的tv"
/>

</LinearLayout>


这是布局文件,那么怎么在程序运行时加载这个布局呢?

public class MainActivity extends ActionBarActivity {

private ViewStub stub;
private boolean isShow = true;
private TextView tv;

/* (non-Javadoc)
* @see android.support.v7.app.ActionBarActivity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//布局的加载有两种方式,一种是stub.inflate();
//另一种是stub.setVisibility(View.VISIBLE);
stub = (ViewStub) this.findViewById(R.id.vs);
//      stub.inflate();
stub.setVisibility(View.VISIBLE);
//实例化之后就可以拿到stub布局的根节点,然后可以对之进行操作
View root = this.findViewById(R.id.inflated_id);
//注意要先实例化stub,然后才可以拿到tv
tv = (TextView) root.findViewById(R.id.tv);
root.setBackgroundColor(Color.BLUE);
}

public void onClick(View v){
switch (v.getId()) {
case R.id.toggle:
if (isShow) {
stub.setVisibility(View.GONE);
}else{
stub.setVisibility(View.VISIBLE);
tv.setText("---");
}
isShow = !isShow;
break;

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