在做項目中,我們經常會複用一些相同的頁面佈局,爲了避免過多的代碼重複,我們把這些頁面提取出來,有兩種方式去實現頁面重用
方式一:在layout頁面中包含另外一個頁面
<include layout="@layout/top" />
方式二:這個方法會比較好,如果包含的頁面有點擊效果以及其他內容操作的話,可以避免很多代碼重複
步驟一:創建好重用的代碼layout佈局頁面 top.xml(頁面中就兩個點擊按鈕分別是btn1,btn2)
步驟三:最主要的步驟,創建TopLayout繼承LinearLayout,讓它成爲我們自定義控件
public class TopLayout extends LinearLayout{
//重寫了LinearLayout帶有兩個參數的構造函數
public Top(Context context, AttributeSet attrs) {
super(context, attrs);
//加載top頁面
LayoutInflater.from(context).inflate(R.layout.top, this);
Button btn=(Button) findViewById(R.id.btnOK);
Button btn2=(Button) findViewById(R.id.btnCANCLE);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "點擊了OK按鈕", Toast.LENGTH_SHORT).show();
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "點擊了CANCLE按鈕", Toast.LENGTH_SHORT).show();
//點擊btnOK銷燬當前的活動
((Activity)getActivity()).finish();
}
});
}
}
步驟四:頁面引用自定義控件
//[com.activity.TopLayout]是TopLayout所在位置全名稱
<com.activity.TopLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.activity.Top>
這樣就成功啦!