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

Android 自定義 View 組件與自定義屬性實現詳解

編輯:關於 Android 程式設計

在實際開發中,系統提供的現成視圖往往無法滿足特定需求,這時我們就需要自己創建自定義 View。做法很簡單:繼承現有的 View(或它的子類),然後重寫需要的方法即可。

第一步:自定義 View

以下示例繼承 TextView,並在構造方法中把文字顏色設為藍色:

public class MyTextView extends TextView {
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setTextColor(Color.BLUE); // 將字體設置為藍色
    }
}

完成後,就可以在布局文件中直接使用這個自定義 View:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.example.myviewtest.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />
</RelativeLayout>

第二步:定義自定義屬性

如果希望像 android:layout_height="wrap_content" 那樣自定義屬性,就需要用到 declare-styleable。它專門用於為自定義控件添加自定義屬性。

首先在 res/values 目錄下新建 myAttrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyTextView">
        <attr name="fontSize" format="dimension" />
    </declare-styleable>
</resources>

其中:

  • name="MyTextView" 會在 R.java 中生成對應的引用名。
  • <attr name="fontSize" format="dimension" /> 定義了自定義屬性名稱,R.java 中會生成 MyTextView_fontSize。
  • format 用於聲明該屬值的類型(此處為 dimension 尺寸)。

第三步:在布局中使用自定義屬性

在布局文件裡,需要通過 xmlns 聲明指向 R.java 所在包的命名空間:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:mytextview="https://schemas.android.com/apk/res/com.example.myviewtest"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <com.example.myviewtest.MyTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        mytextview:fontSize="20dp"
        android:text="text size = 20dp" />
    <com.example.myviewtest.MyTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        mytextview:fontSize="15dp"
        android:text="text size=15dp" />
</LinearLayout>

其中 xmlns:mytextview 的地址指向 R.java 所在的包目錄。

第四步:在代碼中讀取屬性值

最後在 MyTextView 中通過 TypedArray 讀取並應用自定義屬性的值:

public class MyTextView extends TextView {
    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
        this.setTextSize(ta.getDimension(R.styleable.MyTextView_fontSize, 10));
        ta.recycle();
    }

    public MyTextView(Context context) {
        super(context);
    }
}

通過以上四步,就完成了一個帶自定義屬性的可複用 View 組件。

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