android 自訂View(1)

來源:互聯網
上載者:User

標籤:

自訂View:

第一步:建立一個View的實作類別, 建立構造器和重寫onDraw() 和onMesure()等方法。

 

TypedArray擷取自訂View的屬性的數組
context.obtainStyledAttributes(attrs, R.styleable.MyView); 
// 從數組中根據styleable中定義的對應屬性的值   
屬性是自訂View的名+“-”+屬性名稱===》MyView_textColor
int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00); 
設定畫筆的屬性:mPaint.setColor(textColor);

 

 

 

/**   * 這個是自訂的TextView.   * 至少需要重載構造方法和onDraw方法   * 對於自訂的View如果沒有自己獨特的屬性,可以直接在xml檔案中使用就可以了   * 如果含有自己獨特的屬性,那麼就需要在建構函式中擷取屬性檔案attrs.xml中自訂屬性的名稱   * 並根據需要設定預設值,放在在xml檔案中沒有定義。   * 如果使用自訂屬性,那麼在應用xml檔案中需要加上新的schemas,   * 比如這裡是xmlns:my="http://schemas.android.com/apk/res/demo.view.my"   * 其中xmlns後的“my”是自訂的屬性的首碼,res後的是我們自訂View所在的包   * @author Administrator   *   */  public class MyView extends View {              Paint mPaint; //畫筆,包含了畫幾何圖形、文本等的樣式和顏色資訊       public MyView(Context context) {           super(context);       }              public MyView(Context context, AttributeSet attrs){           super(context, attrs);           mPaint = new Paint();           //TypedArray是一個用來存放由context.obtainStyledAttributes獲得的屬性的數組           //在使用完成後,一定要調用recycle方法           //屬性的名稱是styleable中的名稱+“_”+屬性名稱           TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);           int textColor = array.getColor(R.styleable.MyView_textColor, 0XFF00FF00); //提供預設值     ,放置未指定           float textSize = array.getDimension(R.styleable.MyView_textSize, 36);           mPaint.setColor(textColor);           mPaint.setTextSize(textSize);          array.recycle(); //一定要調用,否則這次的設定會對下次的使用造成影響       }              public void onDraw(Canvas canvas){           super.onDraw(canvas);           //Canvas中含有很多畫圖的介面,利用這些介面,我們可以畫出我們想要的圖形           //mPaint = new Paint();           //mPaint.setColor(Color.RED);           mPaint.setStyle(Style.FILL); //設定填充           canvas.drawRect(10, 10, 100, 100, mPaint); //繪製矩形                      mPaint.setColor(Color.BLUE);           canvas.drawText("我是被畫出來的", 10, 120, mPaint);       }   }  

 

第二步:在/res/values/下建立一個attrs檔案,添加<declare--styleable/>

<!-- 自訂屬性 --> <declare-styleable name="MyView">     <attr name="textColor" format="color"/>     <attr name="textSize" format="dimension"/> </declare-styleable>

    第三步:在布局檔案中添加命名空間,便於引用在attrs.xml檔案中自訂的屬性

    

    

    

  

android 自訂View(1)

聯繫我們

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