天天看點

android 自定義屬性

1.先在res/values檔案夾中建立一個attrs.xml檔案

<?xml version="1.0" encoding="utf-8"?> 

<resources> 

    <declare-styleable name="MyView"> 

        <attr name="textColor" format="color" /> 

        <attr name="textSize" format="dimension" /> 

    </declare-styleable> 

</resources>

2.建立一個MyView.java。用來在螢幕上畫一個矩形和一個字元串。

package com.MyAndroid;

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{

    public Context mContext;

    public Paint mPaint;

    public MyView(Context context) {

        super(context);

        mContext = context;

    }

    public MyView(Context context, AttributeSet attrs) {

        super(context, attrs);

        mPaint = new Paint();

         //将MyView中attrs屬性值放入a中

         TypedArray a = context.obtainStyledAttributes(attrs, 

                    R.styleable.MyView); 

          int textColor = a.getColor(R.styleable.MyView_textColor,Color.RED); 

          float textSize = a.getDimension(R.styleable.MyView_textSize, 36); 

          //設定預設的字型大小   

          mPaint.setTextSize(textSize);

          //設定預設的畫筆顔色 

          mPaint.setColor(textColor); 

          //最後一定要使用這個方法。将設定好的a傳回給StyledAttributes,後面可以重新使用。

          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.GREEN);

        canvas.drawText("丹", 110,110,mPaint);

三、将我們自定義的MyView 加入布局main.xml 檔案中,平且使用自定義屬性,自定義屬性必須加上:

xmlns:test ="http://schemas.android.com/apk/res/com.MyAndroid "藍色 是自定義屬性的字首,紅色 是我們包名.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:test="http://schemas.android.com/apk/res/com.MyAndroid" 

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<com.MyAndroid.MyView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    test:textSize="20px" 

    test:textColor="#fff"   

/>

</LinearLayout>

4.運作效果

android 自定義屬性

還有就是當聲明declare-styleable的時候,format可以有一下格式:

reference

string

color

dimension

boolean

integer

float

fraction

enum

flag

轉自http://ssd910.blog.163.com/blog/static/23876797201072504136476/

    http://blog.csdn.net/G_rrrr/archive/2009/11/24/4861290.aspx

第二篇裡還有android自帶Button的實作代碼,學習起來挺不錯的。

繼續看貪吃蛇了。。吃啊吃,明天就可以吃粽子了~!