Button- 自定义控件添加自定义属性

今天自定义了一个button按钮,需要添加一个属性,具体步骤如下

1.新属性的信息设定:在values目录下添加attrs.xml文件,在里面添加属性信息

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

    <declare-styleable name="ColorButton">
        <attr name="textNumber" format="reference|string" />
    </declare-styleable>

</resources>

2.在xml中添加

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myattr="http://schemas.android.com/apk/res/com.android.calculator2"
    android:id="@+id/simplePad"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:divider="@drawable/horizontal_line"
    android:orientation="vertical"
    android:showDividers="middle" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:divider="@drawable/vertical_line"
        android:showDividers="middle" >

        <com.android.calculator2.ColorButton
            android:id="@+id/cle"
            style="@style/simple_button_style" />

        <com.android.calculator2.ColorButton
            android:id="@+id/del"
            style="@style/simple_button_style" />

        <com.android.calculator2.ColorButton
            android:id="@+id/div"
            style="@style/simple_button_style"
            myattr:textNumber="@string/div" />

        <com.android.calculator2.ColorButton
            android:id="@+id/mul"
            style="@style/simple_button_style"
            android:contentDescription="@string/divDesc"
            myattr:textNumber="@string/mul" />
    </LinearLayout>

 </LinearLayout>

 

这里有一点要注意,就是必须添加一条语句xmlns:myattr="http://schemas.android.com/apk/res/com.android.calculator2"  格式为xmlns:自己起个名字=“//schemas.android.com/apk/res/自己应用的包名”这个名字你会发现他的用处,就是在引用这个资源的时候,添加了一个区域前缀,就像android:text 自定义的使用就是myattr:textNumber

3.在代码中的引用

代码如下

package com.android.calculator2;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Button;

class ColorButton extends Button implements OnClickListener {
    int CLICK_FEEDBACK_COLOR;
    static final int CLICK_FEEDBACK_INTERVAL = 10;
    static final int CLICK_FEEDBACK_DURATION = 350;

    private String mText;
    float mTextX;
    float mTextY;
    long mAnimStart;
    OnClickListener mListener;

    public ColorButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        Calculator calc = (Calculator) context;
        mListener = calc.mListener;
        setOnClickListener(this);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ColorButton);
        int resourceId = a.getResourceId(R.styleable.ColorButton_textNumber, 0); 
        mText = resourceId < 0 ? "" : a.getString(R.styleable.ColorButton_textNumber);
        a.recycle();
    }   

    public void onClick(View view) {
        mListener.onClick(this);
    }   

    @Override
    public void onSizeChanged(int w, int h, int oldW, int oldH) {
        measureText();
    }   
 private void measureText() {
        Paint paint = getPaint();
        mTextX = (getWidth() - paint.measureText(getText().toString())) / 2;
        mTextY = (getHeight() - paint.ascent() - paint.descent()) / 2;
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        measureText();
    } 
//添加图片背景
 
public StateListDrawable setbg(TypedArray normal, TypedArray prossed, int drawableId) { StateListDrawable bg = new StateListDrawable(); Drawable normal_state = normal.getDrawable(drawableId); Drawable pressed_state = prossed.getDrawable(drawableId); bg.addState(new int[] { android.R.attr.state_pressed }, pressed_state); bg.addState(new int[] { -android.R.attr.state_pressed }, normal_state); return bg; } public String getTextNumber() { return mText; } }

注意:int resourceId = a.getResourceId(R.styleable.ColorButton_textNumber, 0)的时候,必须是attrs 中declare-styleable的名字+下划线+属性名

对这个类的引用的地方如下

  TypedArray simpleButtons = res.obtainTypedArray(R.array.simple_buttons_id);
            TypedArray advanceButtons = res.obtainTypedArray(R.array.advance_buttons_id);

            TypedArray imagesAdvanceNormal = res.obtainTypedArray(R.array.advance_drawable_normal);
            TypedArray imagesAdvancePressed = res.obtainTypedArray(R.array.advance_drawable_pressed);
            TypedArray imagesSimpleNormal = res.obtainTypedArray(R.array.simple_drawable_normal);
            TypedArray imagesSimplePressed = res.obtainTypedArray(R.array.simple_drawable_pressed);
            for (int i = 0; i < simpleButtons.length(); i++) {
                final ColorButton button = (ColorButton) simplePage.findViewById(simpleButtons
                        .getResourceId(i, 0));
                StateListDrawable drawable = button.setbg(imagesSimpleNormal,
                        imagesSimplePressed, i); 
                button.setBackgroundDrawable(drawable);
            }   
            for (int i = 0; i < advanceButtons.length(); i++) {
                final ColorButton button = (ColorButton) advancedPage.findViewById(
                        advanceButtons.getResourceId(i, 0));
                StateListDrawable drawable = button.setbg(imagesAdvanceNormal,
                        imagesAdvancePressed, i); 
                button.setBackgroundDrawable(drawable);
            }   
            imagesSimpleNormal.recycle();
            imagesSimplePressed.recycle();
            imagesAdvanceNormal.recycle();
            imagesAdvancePressed.recycle();

补充:

对于format属性

如下

<!--reference:参考某一资源ID--> 
<!--属性定义-->
<declare-styleable name="名称">
<attr format="reference" name="background" />
</declare-styleable>
<!--属性使用-->
<ImageView
android:layout_width="42dip"
android:layout_height="42dip"
android:background="@drawable/图片ID" />
<!--color:颜色值-->
<!--属性定义-->
<declare-styleable name="名称">
<attr format="color" name="textColor" />
</declare-styleable>
<!--属性使用-->
<TextView
android:layout_width="42dip"
android:layout_height="42dip"
android:textColor="#00FF00" />
<!--boolean:布尔值-->
<!--属性定义-->
<declare-styleable name="名称">
<attr format="boolean" name="focusable" />
</declare-styleable>
<!--属性使用-->
<Button
android:layout_width="42dip"
android:layout_height="42dip"
android:focusable="true" />
<!--dimension:尺寸值-->
<!--属性定义-->
<declare-styleable name="名称">
<attr format="dimension" name="layout_width" />
</declare-styleable>
<!--属性使用-->
<Button
android:layout_width="42dip"
android:layout_height="42dip" />
<!--float:浮点值-->
<!--属性定义-->
<declare-styleable name="AlphaAnimation">
<attr format="float" name="fromAlpha" />
<attr format="float" name="toAlpha" />
</declare-styleable>
<!--属性使用-->
<alpha
android:fromAlpha="1.0"
android:toAlpha="0.7" />
<!--integer:整型值-->
<!--属性定义-->
<declare-styleable name="AnimatedRotateDrawable">
<attr format="integer" name="frameDuration" />
<attr format="integer" name="framesCount" />
</declare-styleable>
<!--属性使用-->
<animated-rotate
android:frameDuration="100"
android:framesCount="12"
/>
<!--string:字符串-->
<!--属性定义-->
<declare-styleable name="MapView">
<attr format="string" name="apiKey" />
</declare-styleable>
<!--属性使用-->
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0jOkQ80oD1JL9C6HAja99uGXCRiS2CGjKO_bc_g" />
<!--fraction:百分数-->
<!--属性定义-->
<declare-styleable name="RotateDrawable">
<attr format="fraction" name="pivotX" />
<attr format="fraction" name="pivotY" />
</declare-styleable>
<!--属性使用-->

<rotate
android:pivotX="200%"
android:pivotY="300%"
/>
<!--enum:枚举值-->
<!--属性定义-->
<declare-styleable name="名称">
<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
</declare-styleable>
<!--属性使用-->

<LinearLayout
android:orientation="vertical" >
</LinearLayout>
<!--flag:位或运算-->
<!--属性定义-->
<declare-styleable name="名称">
<attr name="windowSoftInputMode">
<flag name="stateUnspecified" value="0" />
<flag name="stateUnchanged" value="1" />
<flag name="stateHidden" value="2" />
<flag name="stateAlwaysHidden" value="3" />
<flag name="stateVisible" value="4" />
<flag name="stateAlwaysVisible" value="5" />
<flag name="adjustUnspecified" value="0x00" />
<flag name="adjustResize" value="0x10" />
<flag name="adjustPan" value="0x20" />
<flag name="adjustNothing" value="0x30" />
</attr>
</declare-styleable>
<!--属性使用-->
<activity
android:windowSoftInputMode="stateUnspecified | stateUnchanged | stateHidden" >
</activity>
<!--注意:属性定义时可以指定多种类型值-->

<declare-styleable name="名称">
<attr format="reference|color" name="background" />
</declare-styleable>

<ImageView
android:layout_width="42dip"
android:layout_height="42dip"
android:background="@drawable/图片ID|#00FF00" />
原文地址:https://www.cnblogs.com/zhangshuli-1989/p/zhangshuli_button_150212103.html