天天看點

Android控件詳解之惰性裝載控件

我将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");
		}
	}
}