要設計一個良好的view組件,需要通過XML屬性來指定他的樣式與行爲。所以我們需要掌握如何定義自定義屬性以及指定屬性值。
第一步:在/res/values下,建立attrs.xml,我測試可以不是attrs.xml這個文件名,不過建議採用attrs.xml來命名。我們在attrs.xml中定義view的屬性,先來看看我的例子:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomText">
<attr name="texttitle" format="string"></attr>
<attr name="textcolor" format="color"></attr>
<attr name="textsize" format="dimension"></attr>
<attr name="textbackground" format="reference"></attr>
</declare-styleable>
</resources>
其中:
- resources標籤用來表示這是一個資源文件;
- declare-styleable後面的name是實例的名字,通常和自定義的view名字一致。這個標籤你可以刪除不用,如果刪除的話,我們無法通過R類來獲取屬性的內容。具體可以參考鴻洋大師寫的Android 深入理解Android中的自定義屬性 。有了這個標籤,我們會發現R類中有一個內部類styleable。對於上面的xml中,你會發現再內部類styleable存在這麼4個常量:
public static final int CustomText_texttitle = 0;
public static final int CustomText_textcolor = 1;
public static final int CustomText_textsize = 2;
public static final int CustomText_textbackground = 3;
你會發現這些常亮的前面的命名跟declare-styleable name後面定義的名稱一樣。像這些細節我們要關注下,說不定什麼時候有用。 attr後面就是給view定義的屬性,上面聲明瞭4個屬性:texttitle、textcolor、textsize、textbackground,format是該屬性的取值類型。關於view的屬性已經format取值請參考: Android自定義屬性,format詳解 。
第二步:一旦定義好自設的屬性,就可以再layout XML中使用它們,但是由於自設的屬性歸屬不同的命名空間,不是屬於http://schemas.android.com/apk/res/android,他們歸屬於http://schemas.android.com/apk/res/[your package name]。例如我準備講的一個例子的layout xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res/com.uudou.study.customattr"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<com.uudou.study.customattr.CustomText
android:layout_width="200dp"
android:layout_height="200dp"
custom:texttitle="1234"
custom:textcolor="#ff0000"
custom:textsize="40px"
custom:textbackground="@drawable/bg"
/>
</RelativeLayout>
custom:textbackground=”@drawable/bg,我res/drawable中導入了一張bg.png圖片。方法很簡單,先複製需要拷貝的bg.png圖片,選中drawable,Ctrl+v複製會彈出一個提示框,如下:點OK就會看到圖片在drawable下了
好,今天就到這裏,下節分享我設計帶背景圖片的view的學習過程。
參考:
http://hukai.me/android-training-course-in-chinese/ui/custom-view/create-view.html
http://blog.csdn.net/jdsjlzx/article/details/43452927
http://blog.csdn.net/lmj623565791/article/details/45022631/
http://blog.csdn.net/vipzjyno1/article/details/23696537