我将Android控件的惰性装载控件的学习知识总结一下和大家共享包括(ViewStub)
在Android开发中,如果有用过<include>标签,应该知道该标签可以在布局文件中引用另外一个布局文件,并可以覆盖被引用布局文件根节点所有与布局相关的属性,也就是以“android:layout”开头的属性。通过<include>标签可以将一个非常庞大的布局文件分解成若干个较小的布局文件,而且这些小布局文件可以多次被引用。
<include>标签固然好用,但是有一个问题就是布局文件中的控件不一定在程序启动时就全部都用到,有一些控件只是在一定情况才会用到。而VIewStub控件与<include>标签基本相同,但是唯一不同的是ViewStub不会马上装载引用的布局文件,只有调用ViewStub.inflate或者ViewStub.setVisibility(View.VISIBLE),才会装载引用。
下面看一个例子:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="我的按钮"
android:onClick="onClick_Button" />
<!-- <include layout="@layout/custom" /> -->
<ViewStub android:id="@+id/viewstub" android:inflatedId="@+id/button_layout"
android:layout="@layout/custom" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
custom.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="按钮1" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="按钮2" />
</LinearLayout>
java实现;
<pre name="code" class="html">public class Main extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick_Button(View v)
{
View view = findViewById(R.id.viewstub);
if (view != null)
{
//view = ((ViewStub) view).inflate();
((ViewStub)view).setVisibility(View.VISIBLE);
}
else
{
setTitle("view is null");
}
}
}