安卓创建自定义按钮

一、创建按钮样式

在drawable下创建一个xml文件,用来描述按键的样式:边框颜色及宽度,圆角半径等。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 填充的颜色 -->
    <solid android:color="#ffff" />
        <!-- 边框颜色 -->
    <stroke android:color= "#2196F3"
        android:width="2dip"/>
    <!-- android:radius 弧形的半径 -->
    <!-- 设置按钮的四个角为弧形 -->
    <corners
        android:radius="10dip" />
</shape>

二、如果需要多TEXT显示的话,在values下创建xml文件定义按键的文本集合:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="custom_button_text">
        <attr name="Text_title" format="string"/>
        <attr name="Text_data"  format="string"/>
    </declare-styleable>
</resources>

三、创建自定义custombutton类继承于Button

    在构造函数里 获取按键的样式和文本集合

public MyCustomButton(Context context, AttributeSet attrs){
    super(context,attrs);
    Button_LED = false;
        //获取圆角按钮样式
    setBackgroundResource(R.drawable.my_circle_button_shape);
     //获取按钮包含的TEXT文本元素
    TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.custom_button_text);
    Text_title = ta.getString(R.styleable.custom_button_text_Text_title);
    Text_data = ta.getString(R.styleable.custom_button_text_Text_data);
    ta.recycle();
}

增加了一个指示灯,表示按钮状态

private void drawCustomButton(Canvas canvas){

        if(Button_LED){
            paint.setColor(ContextCompat.getColor(getContext(),android.R.color.holo_green_dark));
            canvas.drawCircle(getWidth() - 32,32,20,paint);
        }else{
            paint.setColor(ContextCompat.getColor(getContext(),android.R.color.darker_gray));
            canvas.drawCircle(getWidth() - 32,32,20,paint);
        }
    }

在onDraw方法里面绘制text文本,指示灯以及想要放置的图片

    protected void onDraw(Canvas canvas){

        drawCustomButton(canvas);
        super.onDraw(canvas);
        if(Text_title == null){
            Text_title = "Device";
        }
        if(Text_data == null){
            Text_data = "Device";
        }
        Paint paint1 = new Paint();
        paint1.setTextSize(72);
        float tagWidth = paint1.measureText(Text_title);
        int x = (int) (getWidth() - tagWidth + bitmp.getWidth())/2;
        int y = this.getHeight()/2;
        canvas.drawText(Text_title,x,y,paint1);
        Paint paint2 = new Paint();
        paint2.setTextSize(this.getHeight()/5);
        paint2.setColor(Color.BLUE);
        float tagWidth2 = paint2.measureText(Text_data);
        int x2= (int) (getWidth() - tagWidth2+ bitmp.getWidth())/2;
        int y2 = this.getHeight()-getHeight()/8;
        canvas.drawText(Text_data,x2,y2,paint2);


        canvas.drawBitmap(bitmp,28,28,paint2);
    }

添加设置LED状态及文本的方法

 public void setCustomButtonLed(boolean isOn){
        this.Button_LED = isOn;
        invalidate();
    }
    public void setCustomButtonText_Title(String text_title){
        this.Text_title = text_title;
        invalidate();
    }
    public void setCustomButtonText_Data(String text_data){
        this.Text_data = text_data;
        invalidate();
    }

由于上传的图片比按钮大需要做一个比例调整,所以添加了一个比例调节的方法

 private Bitmap scaleBitmap(Bitmap origin, float scale) {
        if (origin == null) {
            return null;
        }
        int height = origin.getHeight();
        int width = origin.getWidth();
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (!origin.isRecycled()) {
            origin.recycle();
        }
        return newBM;
    }

四,自定义按钮的使用

在布局文件中添加如下代码:

<com.example.uitest.MyCustomButton
    android:id="@+id/myCustomButton"
    android:layout_width="0dp"
    android:layout_height="111dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.01999998" />

显示效果:

如果想改变文本可以在程序中调用之前定义的方法即可:

myButton.setCustomButtonLed(true);
myButton.setCustomButtonText_Title("第一机房");
myButton.setCustomButtonText_Data("温度A:25.5   温度B:17.8");

实际效果:

 五、自定义控件类的全部代码:

package com.example.uitest;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AndroidException;
import android.util.AttributeSet;
import android.widget.Button;

import androidx.core.content.ContextCompat;

public class MyCustomButton extends androidx.appcompat.widget.AppCompatButton {
    public boolean Button_LED;
    public String Text_title= "Device_1",Text_data = "设备不在线";
    private Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.temp);
    private Bitmap bitmp = scaleBitmap(bitmap,0.3f);
    private Paint paint ;
    public MyCustomButton(Context context, AttributeSet attrs){
        super(context,attrs);
        Button_LED = false;
        paint = new Paint();
        setBackgroundResource(R.drawable.my_circle_button_shape);
        TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.custom_button_text);
        Text_title = ta.getString(R.styleable.custom_button_text_Text_title);
        Text_data = ta.getString(R.styleable.custom_button_text_Text_data);
        ta.recycle();
    }
    private void drawCustomButton(Canvas canvas){

        if(Button_LED){
            paint.setColor(ContextCompat.getColor(getContext(),android.R.color.holo_green_dark));
            canvas.drawCircle(getWidth() - 32,32,20,paint);
        }else{
            paint.setColor(ContextCompat.getColor(getContext(),android.R.color.darker_gray));
            canvas.drawCircle(getWidth() - 32,32,20,paint);
        }
    }
    protected void onDraw(Canvas canvas){

        drawCustomButton(canvas);
        super.onDraw(canvas);
        if(Text_title == null){
            Text_title = "Device";
        }
        if(Text_data == null){
            Text_data = "Device";
        }
        Paint paint1 = new Paint();
        paint1.setTextSize(72);
        float tagWidth = paint1.measureText(Text_title);
        int x = (int) (getWidth() - tagWidth + bitmp.getWidth())/2;
        int y = this.getHeight()/2;
        canvas.drawText(Text_title,x,y,paint1);
        Paint paint2 = new Paint();
        paint2.setTextSize(this.getHeight()/5);
        paint2.setColor(Color.BLUE);
        float tagWidth2 = paint2.measureText(Text_data);
        int x2= (int) (getWidth() - tagWidth2+ bitmp.getWidth())/2;
        int y2 = this.getHeight()-getHeight()/8;
        canvas.drawText(Text_data,x2,y2,paint2);


        canvas.drawBitmap(bitmp,28,28,paint2);
    }
    public void setCustomButtonLed(boolean isOn){
        this.Button_LED = isOn;
        invalidate();
    }
    public void setCustomButtonText_Title(String text_title){
        this.Text_title = text_title;
        invalidate();
    }
    public void setCustomButtonText_Data(String text_data){
        this.Text_data = text_data;
        invalidate();
    }
    /**
     * 根据给定的宽和高进行拉伸
     *
     * @param origin 原图
     * @param scale  缩放比例
     * @return new Bitmap
     */
    private Bitmap scaleBitmap(Bitmap origin, float scale) {
        if (origin == null) {
            return null;
        }
        int height = origin.getHeight();
        int width = origin.getWidth();
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);// 使用后乘
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (!origin.isRecycled()) {
            origin.recycle();
        }
        return newBM;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值