Android高手之路之Android中的自訂屬性attr.xml、TypedArray的使用

來源:互聯網
上載者:User

Android高手之路之Android中的自訂屬性attr.xml、TypedArray的使用

一般我們都是使用android:xxx=...這樣的android的屬性。但有時我們需要使用自訂的屬性,尤其是自訂view的時候尤其需要。

一般需要以下幾個步驟:

1.在res/values 檔案下定義一個attrs.xml 檔案:

 


2.重寫我們的自訂View的構造方法。是使用R.styleable.MyView獲得我們的自訂屬性。

 

TypedArray 通常最後調用 .recycle() 方法,為了保持以後使用該屬性一致性!

 

package com.example.viewdemo;import android.annotation.SuppressLint;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Paint.Style;import android.graphics.Rect;import android.util.AttributeSet;import android.view.View;public class MyView extends View{ private Paint mPaint;  private Context mContext;   private static final String mString = oh,God!;   public MyView(Context context) {          super(context);            }  public MyView(Context context,AttributeSet attrs)      {          super(context,attrs);         mPaint = new Paint();         TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyView);        int textColor = a.getColor(R.styleable.MyView_textColor, 0xffffff);//注意加預設值        float textSize = a.getDimension(R.styleable.MyView_textSize, 36);        mPaint.setTextSize(textSize);        mPaint.setColor(textColor);        a.recycle();    }        @Override    protected void onDraw(Canvas canvas) {    super.onDraw(canvas);        //設定填充        mPaint.setStyle(Style.FILL);        //畫一個矩形,前倆個是矩形左上方座標,後面倆個是右下角座標          canvas.drawRect(new Rect(10, 10, 100, 100), mPaint);          mPaint.setColor(Color.BLUE);        //繪製文字        canvas.drawText(mString, 10, 110, mPaint);    }}

3.將我們的自訂屬性用在XML布局檔案中。注意首碼

 

 

    

運行效果:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.