複合控制項是原子的、可重複使用的widget,它包含多個子控制項,以某種布局方式聯絡在一起。
當你建立一個複合控制項的時候,你需要定義布局,外觀和它包含的Views間的相互作用。複合控制項通過擴充一個ViewGroup建立。為了建立一個複合控制項,你需要選擇一個最適合放置子控制項的layout類來擴充它,如下面的架構代碼所示:
public class MyCompoundView extends LinearLayout {
public MyCompoundView(Context context) {
super(context);
}
public MyCompoundView(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
由於要與Activity一起使用,為複合控制項建立UI的首選方式是使用layout資源。接下來的程式碼片段顯示了一個layout的XML定義,layout定義了一個簡單的widget,由一個EditText和一個Button組成,Button負責清除內容:
<?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”>
<EditText
android:id=”@+id/editText”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
/>
<Button
android:id=”@+id/clearButton”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Clear”
/>
</LinearLayout>
為了使用新的widget的layout,需要重寫它的建構函式,並使用LayoutInflate系統服務的inflate方法來膨脹layout資源。inflate方法帶有layout資源的參數並返回一個膨脹了的View。在這裡的情況下,返回的View應該是你正在建立的類,所以你要傳入一個父View並設定自動把結果附加到父View上。如下面的代碼所示。
下面的代碼顯示了ClearableEditText類。在建構函式裡,它膨脹了上面建立的layout資源,並獲得它裡麵包含控制項的引用。另外,還調用了hookupButton方法,它用來當Button被按下時串連清除文本的功能。
public class ClearableEditText extends LinearLayout {
EditText editText;
Button clearButton;
public ClearableEditText(Context context) {
super(context);
// Inflate the view from the layout resource.
String infService = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li;
li = (LayoutInflater)getContext().getSystemService(infService);
li.inflate(R.layout.clearable_edit_text, this, true);
// Get references to the child controls.
editText = (EditText)findViewById(R.id.editText);
clearButton = (Button)findViewById(R.id.clearButton);
// Hook up the functionality
hookupButton();
}
}
如果你喜歡在代碼裡構建layout,你可以像你為Activity做的一樣去實現。下面的程式碼片段顯示了重寫ClearableEditText建構函式來建立和XML中一樣的UI:
public ClearableEditText(Context context) {
super(context);
// Set orientation of layout to vertical
setOrientation(LinearLayout.VERTICAL);
// Create the child controls.
editText = new EditText(getContext());
clearButton = new Button(getContext());
clearButton.setText(“Clear”);
// Lay them out in the compound control.
int lHeight = LayoutParams.WRAP_CONTENT;
int lWidth = LayoutParams.FILL_PARENT;
addView(editText, new LinearLayout.LayoutParams(lWidth, lHeight));
addView(clearButton, new LinearLayout.LayoutParams(lWidth, lHeight));
// Hook up the functionality
hookupButton();
}
一旦螢幕已經構建完成,你可以為每個子控制項串連事件管理器來提供你需要的功能。在接下來的片段,hookupButton方法填充了當Button按下時清除文本的代碼:
private void hookupButton() {
clearButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
editText.setText(“”);
}
});
}
Sample code:
http://files.cnblogs.com/xirihanlin/DL090722@cc-CompoundControl.zip