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

相关内容

热门资讯

一起来讨论!wpk辅助挂多功能... 一起来讨论!wpk辅助挂多功能透视工具,本来是真的有挂(有挂教学)1、在wpk插件功能辅助器技巧中,...
一分钟快速了解!AAPoKer... 一分钟快速了解!AAPoKer辅助挂多功能透视工具,果然是真的有挂(有挂辅助)1、玩家可以在AAPo...
推荐十款!WPK辅助挂多功能透... 推荐十款!WPK辅助挂多功能透视工具,本来存在有挂(有挂讲解)1、完成WPK辅助器v3.3的残局,帮...
玩家必看科普!德扑之星辅助挂多... 玩家必看科普!德扑之星辅助挂多功能透视工具,一直真的有挂(有挂总结)1、这是跨平台的德扑之星轻量版有...
玩家必看科普!德扑圈辅助挂多功... 玩家必看科普!德扑圈辅助挂多功能透视工具,切实真的是有挂(发现有挂)1、许多玩家不知道德扑圈辅助怎么...
实测教程!WPK辅助挂多功能透... 实测教程!WPK辅助挂多功能透视工具,切实存在有挂(有挂详细)1、操作简单,无需WPK手机版透视脚本...
盘点一款!AAPoKer辅助挂... 盘点一款!AAPoKer辅助挂多功能透视工具,一直是有挂(有挂详情)一、AAPoKer游戏安装教程牌...
玩家科普!智星菠萝德州辅助挂多... 玩家科普!智星菠萝德州辅助挂多功能透视工具,真是是有挂(有挂方法)在进入智星菠萝德州软件靠谱后,参与...
一分钟揭秘!智星菠萝德州辅助挂... 一分钟揭秘!智星菠萝德州辅助挂多功能透视工具,竟然有挂(有挂头条)1、智星菠萝德州免费脚本咨询教程、...
科技新动态!aapoker辅助... 科技新动态!aapoker辅助挂多功能透视工具,好像是真的有挂(了解有挂)1、任何aapoker透视...