標籤:
在畢設項目中多處用到自訂布局,一直打算總結一下自訂布局的實現方式,今天就來總結一下吧。在此之前學習了郭霖大神部落格上面關於自訂View的幾篇博文,感覺受益良多,本文中就參考了其中的一些內容。
總結來說,自訂布局的實現有三種方式,分別是:群組控制項、自繪控制項和繼承控制項。下面將分別對這三種方式進行介紹。
(一)群組控制項
群組控制項,顧名思義就是將一些小的控制群組合起來形成一個新的控制項,這些小的控制項多是系統內建的控制項。比如很多應用中普遍使用的標題列控制項,其實用的就是群組控制項,那麼下面將通過實現一個簡單的標題列自訂控制項來說說群組控制項的用法。
1、建立一個Android項目,建立自訂標題列的布局檔案title_bar.xml:
1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="wrap_content" 5 android:background="#0000ff" > 6 7 <Button 8 android:id="@+id/left_btn" 9 android:layout_width="wrap_content"10 android:layout_height="wrap_content"11 android:layout_centerVertical="true"12 android:layout_margin="5dp"13 android:background="@drawable/back1_64" />14 15 <TextView16 android:id="@+id/title_tv"17 android:layout_width="wrap_content"18 android:layout_height="wrap_content"19 android:layout_centerInParent="true"20 android:text="這是標題"21 android:textColor="#ffffff"22 android:textSize="20sp" />23 24 </RelativeLayout>
可見這個標題列控制項還是比較簡單的,其中在左邊有一個返回按鈕,背景是一張事先準備好的圖片back1_64.png,標題列中間是標題文字。
2、建立一個類TitleView,繼承自RelativeLayout:
1 public class TitleView extends RelativeLayout { 2 3 // 返回按鈕控制項 4 private Button mLeftBtn; 5 // 標題Tv 6 private TextView mTitleTv; 7 8 public TitleView(Context context, AttributeSet attrs) { 9 super(context, attrs);10 11 // 載入布局12 LayoutInflater.from(context).inflate(R.layout.title_bar, this);13 14 // 擷取控制項15 mLeftBtn = (Button) findViewById(R.id.left_btn);16 mTitleTv = (TextView) findViewById(R.id.title_tv);17 18 }19 20 // 為左側返回按鈕添加自訂點擊事件21 public void setLeftButtonListener(OnClickListener listener) {22 mLeftBtn.setOnClickListener(listener);23 }24 25 // 設定標題的方法26 public void setTitleText(String title) {27 mTitleTv.setText(title);28 }29 }
在TitleView中主要是為自訂的標題列載入了布局,為返回按鈕添加事件監聽方法,並提供了設定標題文本的方法。
3、在main_activity.xml中引入自訂的標題列:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:id="@+id/main_layout" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <com.example.test.TitleView 8 android:id="@+id/title_bar" 9 android:layout_width="match_parent"10 android:layout_height="wrap_content" >11 </com.example.test.TitleView>12 13 </LinearLayout>
4、在MainActivity中擷取自訂的標題列,並且為返回按鈕添加自訂點擊事件:
1 private TitleView mTitleBar; 2 mTitleBar = (TitleView) findViewById(R.id.title_bar); 3 4 mTitleBar.setLeftButtonListener(new OnClickListener() { 5 6 @Override 7 public void onClick(View v) { 8 Toast.makeText(MainActivity.this, "點擊了返回按鈕", Toast.LENGTH_SHORT) 9 .show();10 finish();11 }12 });
這樣就用組合的方式實現了自訂標題列,其實經過更多的組合還可以建立出功能更為複雜的自訂控制項,比如自訂搜尋欄等。
(二)自繪控制項
Refer:http://blog.csdn.net/guolin_blog/article/details/17357967
Android自訂布局的三種實現方式