先推薦幾個比較好的博客:http://my.csdn.net/sinyu890807
http://my.csdn.net/dj0379
http://blog.csdn.net/congqingbin/article/details/7869730
這周要去北戴河旅遊,估計要等到下週才能把博客寫完,我這周看的是自定義view這塊,因爲幾乎所以面試都問道自定義view這塊,而這塊正好是我的弱項,所以我趁現在好好看看這塊。
今天寫的是自繪控件的學習心得,案例會放到這個系列的最後一個博客中
自定義view :就是自己編寫控件,不用系統提供的標準控件。
自定義view分爲:(1)自繪控件:繼承view,在onDraw()中自己繪製
(2)組合控件:將系統的控件組合到一起
(3)繼承控件:繼承現有的控件,然後加入一下新的功能
1.繼承控件
繼承已有的控件,重寫構造函數
簡單的案例,繼承TextView,重寫它的屬性
(1)在values下新建一個attrs.xml,用來定義一系列屬性,比如字體顏色,字體大小等等
<?xml version="1.0"
encoding="utf-8"?>
<resources>
<declare-styleable name="CustomTextView">
<attr name="value" format="string"/>
<attr name="textSize" format="float"/>
</declare-styleable>
</resources>
注:
<declare-styleable></declare-styleable>是給自定義控件添加屬性用的,裏面的 name="CustomTextView"表示該屬性集的名字
<attr></attr>表示屬性。裏面的format表示類型(string
, integer , dimension , reference , color , enum......)
這個屬性集合主要是在(2)中獲取其屬性。格式是CustomTextView_value
(2)新建一個類,繼承TextView,在有兩個參數的構造方法中獲取屬性
TypedArray tyArray=context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
this.value=tyArray.getString(R.styleable.CustomTextView_value);
this.textSize=tyArray.getFloat(R.styleable.CustomTextView_textSize, 25);
tyArray.recycle();
this.setText(value);
this.setTextSize(textSize);
this.setTextColor(Color.RED);
(3)在xml中調用寫好的類,
<LinearLayout
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.yang.customviewsemo"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.yang.customviewsemo.customview.CustomTextView
android:id="@+id/custonRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:value="@string/radiobutton_value"
android:textColor="#000000"/>
</LinearLayout>
注:在開頭引用xmlns:custom="http://schemas.android.com/apk/res/com.yang.customviewsemo",res後 面的是項目的包名,然後就可以在佈局界面中引用你定義的屬 性custom:value="@string/radiobutton_value"