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、完成中至手机麻...
我来教大家!pokerist有... 我来教大家!pokerist有挂,微信小程序雀神有外挂码,莫莫娱乐有挂吗(有挂详情)在进入莫莫娱乐有...
一分钟了解!aapoker能玩... 一分钟了解!aapoker能玩,广东雀神麻将开会员胜率高吗,揭秘哈局十三张赢牌秘诀(有挂教程)1、揭...
交流学习经验!wepkoe有外... 交流学习经验!wepkoe有外挂,微信小程序雀神麻雀为什么老是输,微友麻将亲友圈可以调胜率吗(有挂教...
一分钟揭秘!微扑克俱乐部设置,... 一分钟揭秘!微扑克俱乐部设置,雀神互娱辅助器,老友福建棋牌有挂吗(有挂揭秘)1、下载好老友福建棋牌有...
分享给玩家!wpk可以下载io... 分享给玩家!wpk可以下载ios,雀神小程序合作,好运大菠萝吃鸡老是输(有挂细节);1、构建自己的好...
一分钟秒懂!德州之星ai软件,... 一分钟秒懂!德州之星ai软件,广东雀神小程序辅助器最新版,财神十三张可以开挂吗(有挂解说)1、完成广...
实测交流!德扑助手,雀神麻将小... 实测交流!德扑助手,雀神麻将小程序助赢神器购买,阿拉斗牌辅助免费(有挂解密)1、不需要AI权限,帮助...
今日焦点!aapoker有挂,... 今日焦点!aapoker有挂,雀神小程序是正规的吗,易友棋牌有挂吗(有挂技巧)进入游戏-大厅左侧-新...
重大通报!wpk系统发牌规律,... 重大通报!wpk系统发牌规律,广东雀神挂件去哪买,边锋斗地主透明器(有挂介绍)1.边锋斗地主透明器 ...