ViewStub 用于优化布局,类似于操作系统中的理念“运行时调用”,加载布局文件时并不会加载viewstub,只有当调用inflate时才可见。
ViewStub 是一个不可见的,大小为0的View,最佳用途就是实现View的延迟加载,避免资源浪费,在需要的时候才加载View。加载view的方式类似include。
需要注意的是,加载view之后,viewstub本身就会被新加载进来的view替换掉。
见代码。
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android4_test1.MainActivity"
tools:ignore="MergeRootFrame" >
<ViewStub
android:id="@+id/viewstub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:inflatedId="@+id/ss"
android:layout="@layout/viewstub_demo_text_layout" />
</FrameLayout>
inflateId用来索引加载到viewstub的view。
viewstub_demo_text_layout布局文件如下
<TextView
android:id="@+id/viewstub_demo_textview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#aa664411"
android:textSize="16sp"
android:text="I'm here!"/>
<TextView
android:id="@+id/viewstub_demo_textview2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#aa665511"
android:textSize="16sp"
android:text="I'm not here!"/>
它有两个textview。
activity代码
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewStub view = (ViewStub) findViewById(R.id.viewstub);
View view2=view.inflate();
// 或者使用view.setVisibility(View.VISIBLE)间接调用inflate().
/**
* 利用inflatedId访问到填充ViewStub的原布局。
*/
View texView = findViewById(R.id.ss);
TextView textview1=(TextView) texView.findViewById(R.id.viewstub_demo_textview1);
textview1.setText("I have been changed!");
TextView textView=(TextView) view2.findViewById(R.id.viewstub_demo_textview2);
textView.setText("I also have been changed!");
}
}
分别利用inflate()函数的返回值和inflateId设置两个textview的文本显示。