在实际开发中Android中自带的控件有时无法满足我们的需求,这时就需要我们重写控件来实现我们想要的功能。比如我想使Button有按下和弹起效果还可以写文字,就没有哪个原生的控件能满足我们的需求,在这里我选择重载ImageButton,在ImageButton的基础上添加文字
实现效果
重写按钮实现代码
package com.example.buttontest;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageButton;
/**
* 自定义ImageButton 可以在ImageButton上面设置文字
*/
public class CustomImageButton extends ImageButton {
private static final String TAG = "CustomImageButton_dzt";
private String mtext = "a";
private int mcolor = 0;
private float mtextsize = 0f;
private Paint mpatin;
public CustomImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
initAttrs(attrs);
}
private void initAttrs(AttributeSet attrs) {
TypedArray array = getContext().obtainStyledAttributes(attrs,
R.styleable.CustomButtonAttrs);
mtext = array.getString(R.styleable.CustomButtonAttrs_textValue);
mcolor = array.getColor(R.styleable.CustomButtonAttrs_textColor, 230);
mtextsize = array.getDimension(R.styleable.CustomButtonAttrs_textSize,
25.0f);
array.recycle(); // 回收资源
mpatin = new Paint();
mpatin.setTextAlign(Align.CENTER);
Log.d(TAG, "mtextsize = " + mtextsize);
}
public void setText(String text) {
this.mtext = text;
}
public void setColor(int color) {
this.mcolor = color;
}
public void setTextSize(float textsize) {
this.mtextsize = textsize;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mpatin.setColor(mcolor);
mpatin.setTextSize(mtextsize);
canvas.drawText(mtext, canvas.getWidth() / 2,
(canvas.getHeight() / 2) + 6, mpatin);
}
}
自定义控件需要注意几点
1.在view类中有三个构造函数
View(Context context)
Simple constructor to use when creating a view from code.
View(Context context, AttributeSet attrs)
Constructor that is called when inflating a view from XML.
View(Context context, AttributeSet attrs, int defStyleAttr)
Perform inflation from XML and apply a class-specific base style.
自定义的控件如果要在xml中定义就要添加带参数的构造函数
public CustomImageButton(Context context, AttributeSet attrs)
并且要调用父类的构造函数
2.如果要在xml中自定义控件的属性
需要解析attrs参数
private void initAttrs(AttributeSet attrs) {
TypedArray array = getContext().obtainStyledAttributes(attrs,
R.styleable.CustomButtonAttrs);
mtext = array.getString(R.styleable.CustomButtonAttrs_textValue);
mcolor = array.getColor(R.styleable.CustomButtonAttrs_textColor, 230);
mtextsize = array.getDimension(R.styleable.CustomButtonAttrs_textSize,
25.0f);
array.recycle(); // 回收资源
mpatin = new Paint();
mpatin.setTextAlign(Align.CENTER);
Log.d(TAG, "mtextsize = " + mtextsize);
}
R.styleable.CustomButtonAttrs是自定义的属性
attrs.xml定义
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 自定义按钮控件属性 2014.02.25 -->
<declare-styleable name="CustomButtonAtt