最近项目有个需求是实现一个button上显示两个按钮,而且这两行文字可以改变,最终是通过自定义属性来解决的,下面是全部过程和代码:
一、在res/values文件下定义一个attrs.xml文件,format表示参数类型。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="test">
<attr name="tag" format="string" />
<attr name="num" format="integer" />
</declare-styleable>
</resources>
二、自定义一个类,继承Button,获取到自定义的属性,并通过onDraw()方法绘制出来:
public class CustomButton extends Button{
String tag;
int num;
public CustomButton(Context context) {
super(context);
}
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
//获取自定义的属性
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.test);
tag = ta.getString(R.styleable.test_tag);
num = ta.getInteger(R.styleable.test_num, -1);
ta.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制第一行文字
Paint paint = new Paint();
paint.setTextSize(32);
float tagWidth = paint.measureText(tag);
int x = (int) (this.getWidth() - tagWidth)/2;
int y = this.getHeight()/2;
canvas.drawText(tag, x, y, paint);
//绘制第二行文字
Paint paint1 = new Paint();
paint1.setTextSize(28);
paint1.setColor(Color.rgb(0x00,0xff,0x00));
float numWidth = paint.measureText(num + "");
int x1 = (int) (this.getWidth() - numWidth)/2;
int y1 = this.getHeight()/2 + 35;
canvas.drawText(num+"", x1, y1, paint1);
// canvas.translate(0,(this.getMeasuredHeight()/2) - (int) this.getTextSize());
}
}
三、在布局文件中使用,注意,命名空间xmlns可以简写为:xmlns:appNs="http://schemas.android.com/apk/res-auto"。
<?xml version="1.0" encoding="utf-8"?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ljw="http://schemas.android.com/apk/res/com.example.michael.custonview">
<com.example.michael.custonview.CustomButton
android:layout_width="0dp"
android:layout_height="124dp"
android:layout_weight="1"
ljw:tag="大"
ljw:num="12"/>
<com.example.michael.custonview.CustomButton
android:layout_width="0dp"
android:layout_height="124dp"
android:layout_weight="1"
ljw:tag="中"
ljw:num="12"/>
<com.example.michael.custonview.CustomButton
android:layout_width="0dp"
android:layout_height="124dp"
android:layout_weight="1"
ljw:tag="小"
ljw:num="12"/>
<com.example.michael.custonview.CustomButton
android:layout_width="0dp"
android:layout_height="124dp"
android:layout_weight="1"
ljw:tag="特小"
ljw:num="12"/>
</LinearLayout>
最终实现的效果: