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

Android 自訂 View 控制項

編輯:關於 Android 程式設計

自訂 View 概念

自訂 View 可避免在 XML 中重複撰寫相同版面。以下以左右兩個 TextView 的列表項目為例。

準備版面配置

建立 item_list_cus_2.xml,包含標題與內容兩個 TextView。

宣告自訂屬性

在 attrs.xml 中使用 declare-styleable 宣告 title 與 content。

建立自訂 View

public class ItemListCustomText extends RelativeLayout {
    private TextView tvLeft;
    private TextView tvRight;

    public ItemListCustomText(Context context, AttributeSet attrs) {
        super(context, attrs);
        View view = View.inflate(context, R.layout.item_list_custom_2, this);
        tvLeft = (TextView) view.findViewById(R.id.tv_item_list_cus_2_title);
        tvRight = (TextView) view.findViewById(R.id.tv_item_list_cus_2_con);

        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.ItemListCustomText);
        tvLeft.setText(t.getString(R.styleable.ItemListCustomText_title));
        tvRight.setText(t.getString(R.styleable.ItemListCustomText_content));
        t.recycle();
    }

    public void setTitle(String title) {
        tvLeft.setText(title);
    }

    public void setContent(String content) {
        tvRight.setText(content);
    }
}

使用方式

在 XML 中加入自訂命名空間,然後使用 ItemListCustomText,並傳入 title 與 content。

在程式碼中也可呼叫 setTitle 與 setContent 更新內容。

小結

自訂 View 能讓版面配置更簡潔,也方便後續維護。若多個畫面有相同結構,自訂 View 會是很好的選擇。

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