Android自定義View 自定義xml屬性設定
阿新 • • 發佈:2019-01-28
Android自定義View實現很簡單
繼承View,重寫建構函式、onDraw,(onMeasure)等函式。
如果自定義的View需要有自定義的屬性,需要在values下建立attrs.xml。在其中定義你的屬性。
在使用到自定義View的xml佈局檔案中需要加入xmlns:字首="http://schemas.android.com/apk/res/Android專案所在的包路徑即R檔案所在的包(注意:不是自定義view包路徑)". 配置好後按Alt加 / 鍵在使用自定義屬性的時候沒提示自定義屬性程式碼,重啟eclipse可以解決,本人親測。或者寫成:xmlns:my="http://schemas.android.com/apk/res-auto"不過我覺得這個靠譜多了》
在使用自定義屬性的時候,使用字首:屬性名,如my:textColor="#FFFFFFF"。
例項:
- package demo.view.my;
- 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.util.AttributeSet;
- import android.view.View;
- /**
- * 這個是自定義的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
- *
- */
- publicclass 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(); //一定要呼叫,否則這次的設定會對下次的使用造成影響
- }
- publicvoid 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);
- }
- }
相應的屬性檔案:
- <?xmlversion="1.0"encoding="utf-8"?>
- <resources>
- <declare-styleablename="MyView">
- <attrname="textColor"format="color"/>
- <attrname="textSize"format="dimension"/>
- </declare-styleable>
- </resources>
在佈局檔案中的使用:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:my="http://schemas.android.com/apk/res/demo.view.my"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <demo.view.my.MyView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- my:textColor="#FFFFFFFF"
- my:textSize="22dp"
- />
- </LinearLayout>