Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自訂組合控制項

編輯:關於 Android 程式設計

組合控制項概念

自訂組合控制項適合標題欄、設定列等重複使用的畫面。做法是先建立版面配置,再繼承 ViewGroup,並宣告自訂屬性。

建立版面配置

在 setting_view.xml 中放置標題、內容與核取方塊。

宣告自訂屬性

在 values 目錄建立 attrs.xml,使用 declare-styleable 宣告 title 與 content。

自訂 View 類別

public class SettingView extends RelativeLayout {
    private TextView title;
    private TextView content;

    public SettingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        View view = View.inflate(context, R.layout.setting_view, this);
        title = (TextView) view.findViewById(R.id.title);
        content = (TextView) view.findViewById(R.id.content);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SettingView);
        title.setText(a.getString(R.styleable.SettingView_title));
        content.setText(a.getString(R.styleable.SettingView_content));
        a.recycle();
    }
}

使用方式

在 XML 中使用時,需加入自訂命名空間,例如 xmlns:hy 指向 res/套件名稱。然後即可在版面配置中使用該控制項,並傳入標題與內容。

重點

自訂屬性可讓控制項更靈活。透過 TypedArray 取得 XML 設定,再呼叫 setTitle 或 setContent,即可在程式碼中動態更新。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved