自訂view(一),自訂view(

來源:互聯網
上載者:User

自訂view(一),自訂view(

轉載請註明出處:http://blog.csdn.net/ZhouLi_CSDN/article/details/46504881

自訂屬性
使用步驟:1. 通過<declare-styleable>為自訂View添加屬性2. 在xml中為相應的屬性聲明屬性值3. 在運行時(一般為建構函式)擷取屬性值4. 將擷取到的屬性值應用到View在res/values目錄下建立attr.xml檔案<?xml version="1.0" encoding="utf-8"?>  <resources>      <attr name="text" format="string" />    <declare-styleable name="CustomTitleView">          <attr name="text" />    </declare-styleable>  </resources>

format類型:string,color,demension,integer,enum,reference,float,boolean,fraction,flag;
xml布局檔案要引入命名空間:xmlns:custom=”http://schemas.android.com/apk/res/應用程式套件名”
可以參考:[文章]
(http://www.cnblogs.com/angeldevil/p/3479431.html)

擷取自訂屬性:

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0);

自訂view三個建構函式:
1. 一個參數的:java代碼建立view時調用
2. 兩個參數的:在xml建立但是沒有指定style的時候調用
3. 三個參數的:在xml建立指定style時調用

重寫onMeasure方法:

測量控制項和子控制項的寬和高並設定
MeasureSpec的三種模式:
1. EXACTLY:一般是設定了明確的值或者是MATCH_PARENT
2. AT_MOST:表示子布局限制在一個最大值內,一般為WARP_CONTENT
3. UNSPECIFIED:表示子布局想要多大就多大,很少使用

@Override  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  {      int widthMode = MeasureSpec.getMode(widthMeasureSpec);      int widthSize = MeasureSpec.getSize(widthMeasureSpec);      int heightMode = MeasureSpec.getMode(heightMeasureSpec);      int heightSize = MeasureSpec.getSize(heightMeasureSpec);      int width;      int height ;      if (widthMode == MeasureSpec.EXACTLY)      {          width = widthSize;  //直接設定值    } else      {   //根據內容計算大小並設定        mPaint.setTextSize(mTitleTextSize);          mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);          float textWidth = mBounds.width();          int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight());          width = desired;      }    setMeasuredDimension(width, height);  }
onLayout:

設定控制項和子控制項的位置

onDraw:

繪製控制項的內容

onDispatchDraw:

也可以繪製,但是在繪製過程中,系統先向下繪製父view的onDraw,然後子view的onDraw ; 之後在反過來向上調用子view的onDispatchDraw,然後是父view的onDispatchDraw。

所以造成的效果是:

聯繫我們

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