編輯:關於 Android 開發
前面我們已經學過兩種自定義控件的做法——「對現有控件進行擴展」與「直接繼承 View 建立全新視圖」。還沒看過的同學建議補上,看過的也值得回頭複習一遍。把一種技術真正吃透再往下走,比貪多嚼不爛要划算得多;而且光看不成,最好自己動手練一遍,再在原基礎上加點東西,例如補上一兩個功能,這樣技術才真正屬於你。
今天要談的是第三種思路:建立可重複使用的組合控件。先釐清兩個名詞:
· 什麼是「可重複使用」?就是在應用的多個地方共用同一套程式碼。這不只省下工時,還能讓整個 App 的風格保持一致——最典型的例子就是各頁面樣式統一的標題欄。
· 什麼是「組合控件」?顧名思義,就是把多個控件組裝在一起、彼此協作,共同完成某項特定功能。
接下來就以「App 中風格統一的標題欄」為例,走一遍完整實作。
既然是一組組合控件,就需要一個容器來承載。可用的 Layout 很多,這裡選用 RelativeLayout,因為標題欄的「靠左、靠右、居中」正是相對定位最擅長的事。
先定義 CompositeViews 類繼承 RelativeLayout,並把三個版本的建構子寫齊:
public class CompositeViews extends RelativeLayout {
public CompositeViews(Context context) {
this(context, null);
}
public CompositeViews(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CompositeViews(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
接著宣告三個 TextView,分別負責顯示「返回」、「搜尋」與「標題」,並用 LayoutParams 決定它們在容器中的對齊方式:
public class CompositeViews extends RelativeLayout {
private TextView mLeftText;
private TextView mRightText;
private TextView textTitle;
private LayoutParams leftLayoutParams;
private LayoutParams rightLayoutParams;
private LayoutParams titleLayoutParams;
public CompositeViews(Context context) {
this(context, null);
}
public CompositeViews(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CompositeViews(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
initView() 負責初始化這三個子控件:
private void initView(Context context) {
mLeftText = new TextView(context);
mRightText = new TextView(context);
textTitle = new TextView(context);
// 左按鈕:對齊父容器左側
leftLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
leftLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
mLeftText.setText("返回");
mLeftText.setTextSize(22);
// 右按鈕:對齊父容器右側
rightLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rightLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
mRightText.setText("搜尋");
mRightText.setTextSize(22);
// 標題:水平居中
titleLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
titleLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
textTitle.setText("這是一個標題");
textTitle.setTextSize(22);
}
把這個自定義 View 放進布局,再在 Activity 中載入:
activity_main.xml
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
跑一下,畫面出來了:

但問題也很明顯:所有文字、字級、顏色全是寫死的。既然目標是「可複用」,硬編碼絕對不可取。要讓它能被靈活配置,就得靠自定義屬性。
在 res/values/attrs.xml 中,用 declare-styleable 宣告一組屬性集,並為它取一個 name。這個 name 就是我們日後在 XML 中查找整組屬性的入口:
單獨拆解一行來理解:<attr name="titleText" format="string" /> 中,attr 代表一個屬性;name 是這條屬性的名字,我們在 XML 中就是靠它來取值;format 則約束了值的型別,常見的有 string(字串)、dimension(尺寸)、color(顏色)、reference(引用)等。若一個屬性同時接受多種類型,可用 | 串接,例如 reference|color。
使用之前必須先宣告第三方命名空間,加上這一行:
xmlns:custom="https://schemas.android.com/apk/res-auto"
custom 是命名空間的名字,可以任意取,但後續引用自定義屬性時都必須以它開頭。寫法如下:
也就是說,custom:<attr name="..." /> 裡宣告的那個值,例如 custom:titleText="@string/titleText"。
XML 裡設定的值要怎麼取出來?答案是 TypedArray。它封裝了各種從 AttributeSet 中依型別取值的便捷方法。因此我們要修改建構子與 initView():
private void initView(Context context, AttributeSet attrs) {
mLeftText = new TextView(context);
mRightText = new TextView(context);
textTitle = new TextView(context);
/** 讀取自定義屬性 */
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CompositeViews);
String titleText = typedArray.getString(R.styleable.CompositeViews_titleText);
float titleTextSize = typedArray.getDimension(R.styleable.CompositeViews_titleTextSize, 16);
int titleColor = typedArray.getColor(R.styleable.CompositeViews_titleColor, 0);
Drawable titleBackground = typedArray.getDrawable(R.styleable.CompositeViews_titleBackground);
String leftText = typedArray.getString(R.styleable.CompositeViews_leftText);
int leftTextColor = typedArray.getColor(R.styleable.CompositeViews_leftTextColor, 0);
float leftTextSize = typedArray.getDimension(R.styleable.CompositeViews_leftTextSize, 16);
Drawable leftBackground = typedArray.getDrawable(R.styleable.CompositeViews_leftBackground);
String rightText = typedArray.getString(R.styleable.CompositeViews_rightText);
int rightTextColor = typedArray.getColor(R.styleable.CompositeViews_rightTextColor, 0);
float rightTextSize = typedArray.getDimension(R.styleable.CompositeViews_rightTextSize, 16);
Drawable rightBackground = typedArray.getDrawable(R.styleable.CompositeViews_rightBackground);
typedArray.recycle();
// 左按鈕
leftLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
leftLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
mLeftText.setText(leftText);
mLeftText.setTextColor(leftTextColor);
mLeftText.setTextSize(leftTextSize);
mLeftText.setBackground(leftBackground);
addView(mLeftText, leftLayoutParams);
// 右按鈕
rightLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rightLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
mRightText.setText(rightText);
mRightText.setTextColor(rightTextColor);
mRightText.setTextSize(rightTextSize);
mRightText.setBackground(rightBackground);
addView(mRightText, rightLayoutParams);
// 中間標題
titleLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
titleLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
textTitle.setText(titleText);
textTitle.setTextSize(titleTextSize);
textTitle.setTextColor(titleColor);
textTitle.setBackground(titleBackground);
addView(textTitle, titleLayoutParams);
}
流程很直白:先用 context.obtainStyledAttributes() 把屬性集合取進 TypedArray,再用它提供的各型別方法逐項取值,最後套用到各自的控件上。用完記得呼叫 recycle() 回收資源。
至此,標題欄已完全可配置:每個頁面只要在 XML 中放進這個 View 並設定屬性即可,既省開發時間,也讓 App 風格保持一致。
畫面能顯示了,但「返回」和「搜尋」點下去該做什麼?顯然不能寫死在控件裡,否則就談不上複用。常見解法是回呼:控件只負責觸發,功能由調用方決定。
先定義介面:
public interface TopBarClickListener {
void leftClickListener();
void rightClickListener();
}
在建構子中為左右控件掛上點擊事件,但只負責轉發,不實作具體邏輯:
private void setListener() {
mLeftText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTopBarClickListener.leftClickListener();
}
});
mRightText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTopBarClickListener.rightClickListener();
}
});
}
再把介面暴露給外部:
public void setOnTopBarClickListener(TopBarClickListener topBarClickListener) {
mTopBarClickListener = topBarClickListener;
}
最後,誰調用誰實作。這裡只在 MainActivity 中彈個 Toast 示範:
public class MainActivity extends AppCompatActivity {
private CompositeViews topBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topBar = (CompositeViews) findViewById(R.id.topBar);
topBar.setOnTopBarClickListener(new CompositeViews.TopBarClickListener() {
@Override
public void leftClickListener() {
ToastUtil.makeText(MainActivity.this, "您點擊了返回鍵", Toast.LENGTH_SHORT).show();
}
@Override
public void rightClickListener() {
ToastUtil.makeText(MainActivity.this, "您點擊了搜尋鍵", Toast.LENGTH_SHORT).show();
}
});
}
}
成果如下:

需求達成。今天談的是自定義 View 的第三種實作方式,順帶把自定義屬性的宣告與讀取一起走完。建議大家動手做一兩個自己的小例子,把「宣告屬性 → 在 XML 使用 → 用 TypedArray 讀取 → 用介面回呼對外暴露事件」這條鏈路走順,之後再遇到重複的 UI 結構,就知道該怎麼抽象了。
ScrollView 監聽滑到底部的方法
ScrollView 監聽滑到底部的方法 在 Android 中,若希望使用者捲動到 ScrollView 底部時觸發載入更多、顯示按鈕或執行其他行為,可以透過觸控事件與
Android 自定義元件與介面回呼實作
Android 自定義元件與介面回呼實作在 Android 開發中,自定義元件是很常見的需求。當系統提供的控制項無法直接滿足畫面或互動需求時,可以透過繼承 View 或
Android 快速開發框架 ZBLibrary 源碼分享:MVP 架構與標准化開發模板
Android 快速開發框架 ZBLibrary 源碼分享:MVP 架構與標准化開發模板 ZBLibrary 是一套採 MVP 架構的 Android 快速開發框架,目標
Genymotion 模擬器在 Android 開發中的配置方式
Genymotion 簡介 Genymotion 是一套 Android 虛擬環境工具,常用於開發、測試與展示。它通常運行在 VirtualBox 之上,提供比部分內建模