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类即可自定义按钮。

相关内容

热门资讯

透视辅助!微扑克中牌率(wep... 透视辅助!微扑克中牌率(wepoker)外挂透明挂辅助挂(透视)透牌教程(有挂方式)-哔哩哔哩1、很...
一分钟教会你!云扑克(WepO... 一分钟教会你!云扑克(WepOke)外挂透明挂辅助APP(辅助挂)细节方法(有挂详细)-哔哩哔哩;1...
科普常识!欢乐棋牌(wepOk... WePoker透视辅助版本稳定性对比与推荐‌:科普常识!欢乐棋牌(wepOkE)外挂透明挂辅助工具(...
今日焦点!鱼扑克辅助(wePO... 今日焦点!鱼扑克辅助(wePOKE)外挂透明挂辅助脚本(辅助挂)详细教程(有挂教学)-哔哩哔哩;鱼扑...
大家学习交流(轰趴大菠萝)外挂... 《大家学习交流(轰趴大菠萝)外挂透明挂辅助神器(透视)软件透明挂(2025已更新)(哔哩哔哩)》 轰...
一分钟快速了解!cloudpo... 1、一分钟快速了解!cloudpoker云扑克(WEpoke)外挂透明挂辅助挂(透视)解密教程(有挂...
重大通报(wpk插件)外挂透明... 重大通报(wpk插件)外挂透明挂辅助软件(透视)透视辅助(2021已更新)(哔哩哔哩);(需添加指定...
透视辅助!wepoke数据(w... 透视辅助!wepoke数据(wepoker)外挂透明挂辅助工具(透视)必胜教程(有挂方法)-哔哩哔哩...
重大发现(wepokeai)外... 重大发现(wepokeai)外挂透明挂辅助工具(透视)德州ai机器人(有人有挂)-哔哩哔哩1、很好的...
透明神器(微扑克钻石)外挂透明... 透明神器(微扑克钻石)外挂透明挂辅助脚本(透视)透视辅助(2022已更新)(哔哩哔哩);玩家在微扑克...