androidstudio中的自定义按钮
创始人
2024-08-20 21:00:40
0次

使用XML代码,自定义Button类和样式属性来实现自定义按钮。

首先,在XML布局文件中声明自定义Button类并设置样式属性,如下所示:


然后,在Java代码中实现自定义Button类,如下所示:

public class MyButton extends AppCompatButton {
    private int backgroundColor;
    private int textColor;
    private float cornerRadius;

    public MyButton(Context context) {
        super(context);
    }

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyButton);
        backgroundColor = ta.getColor(R.styleable.MyButton_backgroundColor, Color.BLUE);
        textColor = ta.getColor(R.styleable.MyButton_textColor, Color.WHITE);
        cornerRadius = ta.getDimension(R.styleable.MyButton_cornerRadius, 0);
        ta.recycle();

        setBackgroundColor(backgroundColor);
        setTextColor(textColor);
        setCornerRadius(cornerRadius);
    }

    public void setCornerRadius(float cornerRadius) {
        this.cornerRadius = cornerRadius;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setElevation(4);
        }
        GradientDrawable shape = new GradientDrawable();
        shape.setCornerRadius(cornerRadius);
        shape.setColor(backgroundColor);
        setBackground(shape);
    }
}

最后,在styles.xml中声明自定义样式属性,如下所示:


这样,在布局文件中使用MyButton类即可自定义按钮。

相关内容

热门资讯

记者揭秘开挂插件!桃乐甘肃麻将... 记者揭秘开挂插件!桃乐甘肃麻将多功能开挂插件,桃乐甘肃麻将切实有开挂插件1、用户打开应用后不用登录就...
专业讨论辅助工具!抚顺麻将多功... 专业讨论辅助工具!抚顺麻将多功能辅助工具,抚顺麻将一直真的是有辅助工具抚顺麻将是不是有人用挂微扑克w...
重大消息透视器app!重庆蛮籽... 重大消息透视器app!重庆蛮籽麻将多功能透视器app,重庆蛮籽麻将切实真的是有透视器app1、许多玩...
我来教教大家辅助app!营口9... 您好,营口92麻将这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
发现一款辅助器工具!博乐温州棋... 发现一款辅助器工具!博乐温州棋牌多功能辅助器工具,博乐温州棋牌好像存在有辅助器工具1、许多玩家不知道...
玩家必备科技透视器脚本!奥云集... 玩家必备科技透视器脚本!奥云集安麻将多功能透视器脚本,奥云集安麻将都是是有透视器脚本1、奥云集安麻将...
终于知道辅助攻略!牌乐门多功能... 终于知道辅助攻略!牌乐门多功能辅助攻略,牌乐门确实是有辅助攻略1、许多玩家不知道牌乐门辅助怎么退出观...
必看攻略外挂方法!良人麻将多功... 您好,良人麻将这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款...
必备科技辅助软件!千游科技多功... 必备科技辅助软件!千游科技多功能辅助软件,千游科技果然是真的有辅助软件1、每一步都需要思考,不同水平...
一分钟了解作弊器教程!海迅麻将... 一分钟了解作弊器教程!海迅麻将多功能作弊器教程,海迅麻将确实是真的有作弊器教程1、下载好海迅麻将透视...