android自訂控制項(三) 自訂屬性

來源:互聯網
上載者:User

書接上回 

在xml裡建立屬性,然後java代碼裡用typedArray獲得這些屬性,得到屬性後,利用屬性做一些事.例:得到xml裡的color,賦給paint.

1.在res/values/下建立attrs.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="CustomView2">    <attr name="textColor" format="color" />    <attr name="textSize" format="dimension" />    </declare-styleable></resources><!-- name="CustomView1"控制項名稱 得到TypedArray時用 --><!-- name="textColor" 對應test:textColor --><!-- format="color" 對應構造方法裡a.getColor(R.styleable.CustomView2_textColor, 0xFFFFFFFF); -->

format詳解可參照http://blog.csdn.net/ethan_xue/article/details/7315064
2.主要看建構函式

public class CustomView2 extends View {private Paint mPaint2;private String mText = "drawText";public CustomView2(Context context, AttributeSet attrs) {super(context, attrs);mPaint2 = new Paint();// TypedArray是存放資源的array,1.通過上下文得到這個數組,attrs是建構函式傳進來的,對應attrs.xmlTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView2);// 獲得xml裡定義的屬性,格式為 名稱_屬性名稱 後面是預設值int textColor = a.getColor(R.styleable.CustomView2_textColor, 0xFFFFFFFF);float textSize = a.getDimension(R.styleable.CustomView2_textSize, 35);mPaint2.setColor(textColor);mPaint2.setTextSize(textSize);// 為了保持以後使用該屬性一致性,返回一個綁定資源結束的訊號給資源a.recycle();}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);mPaint2.setStyle(Style.FILL);canvas.drawText(mText, 10, 60, mPaint2);}}

3.布局

<?xml version="1.0" encoding="utf-8"?><!-- xmlns:test="http://schemas.android.com/apk/res/ethan.customview1" 包名 --><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:test="http://schemas.android.com/apk/res/ethan.customview1"     android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><ethan.customview1.CustomView2      android:layout_width="wrap_content"     android:layout_height="wrap_content"     test:textColor="#f00"    test:textSize="20sp"    /></LinearLayout>

4.

 http://download.csdn.net/detail/ethan_xue/4108832

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.