系統自帶的控件再豐富,也总有覆盖不到的設計稿。這時候最乾淨的做法不是硬湊,而是自己封裝一個可複用的自定義控件。本文以一個「圖標 + 文字」的橫向按鈕為例,走一遍完整流程:先寫內部布局,再用代碼把它包成一個可以外部配置的控件。
在 res/layout 下新增 imagebtn.xml,用一個橫向的 LinearLayout 裝 ImageView 和 TextView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingBottom="5dip"
android:paddingLeft="40dip"
android:paddingTop="5dip"
android:src="@drawable/right_icon" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="8dip"
android:text="確定"
android:textColor="#000000" />
</LinearLayout>
這一步的重點是把 id 起好,因為下一步要靠 findViewById 把它們抓出來。
接著寫一個繼承 LinearLayout 的類,在構造函數裡把上面的布局 inflate 進來,再對外暴露設定圖片與文字的方法。這樣使用者在 XML 裡寫這個控件、在代碼裡調方法,兩邊都能控制顯示內容。
public class ImageBtn extends LinearLayout {
private ImageView imageView;
private TextView textView;
public ImageBtn(Context context) {
super(context);
}
public ImageBtn(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.imagebtn, this);
imageView = (ImageView) findViewById(R.id.imageView1);
textView = (TextView) findViewById(R.id.textView1);
}
/**
* 設置圖片資源
*/
public void setImageResource(int resId) {
imageView.setImageResource(resId);
}
/**
* 設置顯示的文字
*/
public void setTextViewText(String text) {
textView.setText(text);
}
}
這是被很多初學者忽略的細節:在 XML 布局文件中被解析創建的控件,走的是帶 AttributeSet 的那個構造函數;而用 new 在代碼裡創建的實例,走的是只帶 Context 的構造函數。如果只寫一個,控件在兩種場景下會表現不一致,甚至直接崩潰。養成兩個都寫、並把初始化邏輯放在被 XML 調用的那個裡的習慣,能省下不少排查時間。
完成後,在別的布局裡直接寫 <com.example.ImageBtn /> 就能使用,需要換圖或改文案時調用對應的 setter 即可,做到了「一次封裝,多處複用」。