Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 自定義 View 及 layout 屬性全攻略

編輯:初階開發

對於 Android 的自定義 View,大家想必已不陌生,但關於自定義 View 的屬性添加,以及 Layout 的命名空間問題,不少網友仍不太清楚。今天我們再來系統地複習一遍。

首先,直接用代碼實例化自定義 View:

  CwjView myView = new CwjView(context);

若用於遊戲或整個窗體界面,可以直接在 onCreate 中調用 setContentView(myView);。而若作為一個控件,則可能需要從 Layout 的 XML 中聲明,例如:

  <cn.com.android123.CwjView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
  />

也可以透過父類方式聲明:

  <View class="cn.com.android123.CwjView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
  />

上面僅用了父類 View 的兩個屬性,均來自 android 命名空間。而自定義控件往往具備更多功能,例如:

    <cn.com.android123.CwjView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
  cwj:age="22"
   cwj:university="sjtu"
   cwj:city="shanghai"
   />

這裡的三個屬性由我們自己定義。按照標準 XML 規範,通常還需聲明命名空間,例如 XMLns:android="https://schemas.android.com/apk/res/android"。對於自定義 View,命名空間可寫為 XMLns:cwj="https://schemas.android.com/apk/res/cn.com.android123.cwjView",或直接寫作 XMLns:cwj="https://schemas.android.com/apk/res/android" 都可以。

那麼,如何定義 cwj 命名空間及 age、university、city 這三個屬性呢?在工程的 res/values 目錄中新建一個 cwj_attr.xml 檔案(建議採用 utf-8 編碼),內容如下:

<?XML version="1.0" encoding="utf-8" ?>
<resources>
  <declare-styleable name="CwjView">
  <attr name="age" format="integer" />
  <attr name="city" format="string" />
  <attr name="university" format="string" />
  </declare-styleable>
</resources>

這裡的 format 或許讓人略感陌生。目前 Android 系統內置的格式類型有:integer(如 ProgressBar 的進度值)、float(如 RatingBar 的 3.5 顆星)、boolean(如 ToggleButton 的勾選狀態)、string(如 TextView 的 text 屬性)。除常見基礎類型外,還有 color(顏色,可識別 #FF0000 等)、dimension(尺寸,如 23dip、15px、18sp)以及 reference(引用,如 @+id/cwj、@drawable/xxx)等特殊類型。

那 reference 該在何時使用呢?以定義一個顏色為例:

  <attr name="red" format="color|reference" /> 這裡用邏輯或運算符,定義的紅色既屬於顏色類型,又能被引用。

在自定義類中,我們需要使用 obtainStyledAttributes 方法來獲取定義的屬性。在構造方法 CwjView(Context context, AttributeSet attrs) 中,可以這樣寫:

  public CwjView(Context context, AttributeSet attrs) {
  super(context, attrs);
      TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.cwj_attr);
      mAge = a.getInteger(R.styleable.CwjView_age, 22);
      mCity = a.getString(R.styleable.CwjView_city, "shanghai");
      mUniversity = a.getString(R.styleable.CwjView_university, "sjtu");
      a.recycle(); //不要忘了回收資源
  }

這樣,全局成員變量 mAge、mCity 便拿到了所需內容。若需根据 layout 中的數值動態處理,還可使用 AttributeSet 類的 getAttributeResourceValue 方法:

  public CwjView(Context context, AttributeSet attrs) {
  super(context, attrs);
  resId = attrs.getAttributeResourceValue("cn.com.android123.CwjView", "age", 100);
  resId = attrs.getAttributeResourceValue("cn.com.android123.CwjView", "city", "shanghai");
  //resID就可以任意使用了
  }

以上兩種方法中,參數的最後一個數值均為默認值。掌握這套流程,你就能為自定義 View 添加靈活而規範的屬性了。

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