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

用自定義命名空間,做一個會變色的橫向柱狀圖

編輯:關於 Android 程式設計

先上圖:

效果很簡單:一個 ListView,item 是自定義 View,具備兩個特點——可以傳入長度動態改變柱子長短;並依長度改變色值,越長越偏紅,越短越偏黃。

用到的知識點不過是 Paint 在 Canvas 上作畫,這裡不再贅述。本篇真正想講的是 Android 自定義命名空間 的用法。

為什麼需要命名空間

按常規做法,要往自定義 View 傳值只能調用 setXxx(),前提是該 View 已經被創建出來,而且需要有人主動去調。可我們希望能像構造方法一樣,在 XML 聲明的那一刻就把初始值給定。

回想 XML 裡常見的 android:layout_height="20dp",前面那個 android 就是命名空間,只不過它是系統預設的。我們完全可以自己定義一個命名空間來用。

一、聲明屬性:res/values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="BarChartView">
        <!-- bar_height 表示柱狀圖高度 -->
        <!-- bar_width 表示柱狀圖寬度 -->
        <attr name="bar_height" format="dimension" />
        <attr name="bar_width" format="dimension" />
        <attr name="text" format="string" />
    </declare-styleable>
</resources>

declare-styleable 顧名思義就是「聲明一組樣式屬性」,後續 Java 代碼會從這裡把值取出來。這裡定義了 bar_height、bar_width 兩個尺寸值與一個字串 text。

二、在佈局中使用

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:myxmlns="https://schemas.android.com/apk/res/com.example.simple"
    android:layout_width="wrap_content"
    android:layout_height="match_parent">

    <com.example.simple.BarChartView
        android:id="@+id/cv_chart"
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:layout_centerVertical="true"
        myxmlns:bar_height="40" />

</RelativeLayout>

紅字部分是關鍵:xmlns:myxmlns="https://schemas.android.com/apk/res/com.example.simple"。
定義規則為 xmlns:前綴 = namespaceURI,在 Android 中即 https://schemas.android.com/apk/res/ 加上應用包路徑;使用時則按「前綴:屬性名」的格式書寫。

myxmlns 這個前綴可以隨便取名,但必須與使用處保持一致。聲明好之後,attrs.xml 裡定義的所有屬性就都能用了。

三、在代碼中讀取

public BarChartView(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BarChartView);
    chartHeight = a.getInt(R.styleable.BarChartView_bar_height, 20);
    chartWidth = a.getResourceId(R.styleable.BarChartView_bar_width, 10);
    a.recycle();

    chartHeight = DisplayUtils.Dp2Px(context, chartHeight);
}

兩個細節值得留意:讀取時第二個參數是「XML 未配置時的預設值」,別忘了給;另外 getInt 與 getResourceId 要對應 attrs 中聲明的 format 型別,寫錯會拿到意外結果。取值後記得 recycle。

小結

自此目的達成:屬性直接在 XML 中預設,不必再靠 setXxx 一個個傳參。這套「declare-styleable + obtainStyledAttributes」的組合,幾乎是所有開源自定義控件的標配寫法,值得記牢。

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