gpt4 book ai didi

java - 以编程方式向按钮添加描边

转载 作者:行者123 更新时间:2023-11-30 00:26:55 25 4
gpt4 key购买 nike

有什么方法可以使用 java 而不是 XML 向按钮添加笔划/轮廓?我一直在努力研究它,我遇到的一切都是 XML。

我想要做的是让按钮默认带有黑色边框。然后在按下后颜色会变成红色。

最佳答案

在Java中你可以这样实现,

    public Drawable getMyDrawable() {
StateListDrawable states = new StateListDrawable();

// states.addState(new int[]{
// -android.R.attr.state_enabled,
// }, getDisableDrawable());

states.addState(new int[]{
android.R.attr.state_focused, -android.R.attr.state_pressed,
}, getDrawable(true));
states.addState(new int[]{
android.R.attr.state_focused, android.R.attr.state_pressed,
}, getDrawable(true));
states.addState(new int[]{
-android.R.attr.state_focused, android.R.attr.state_pressed,
}, getDrawable(true));
states.addState(new int[]{
android.R.attr.state_enabled
}, getDrawable(false));

return states;
}

public Drawable getDrawable(boolean pressed) {
Drawable[] normalDrawable = new Drawable[2];
normalDrawable[0] = getRectBorder(pressed);
normalDrawable[1] = getRectBG();

LayerDrawable layerDrawable = new LayerDrawable(normalDrawable);
layerDrawable.setLayerInset(1, 2, 2, 2, 2);

return layerDrawable.mutate();
}

public Drawable getRectBorder(boolean pressed) {
RectShape rectShape = new RectShape();
ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
shapeDrawable.getPaint().setColor(pressed ? Color.RED : Color.BLACK);
shapeDrawable.getPaint().setStyle(Paint.Style.STROKE);
shapeDrawable.getPaint().setStrokeWidth(2);
shapeDrawable.getPaint().setAntiAlias(true);
shapeDrawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
return shapeDrawable.mutate();
}

public Drawable getRectBG() {
RectShape rectShape = new RectShape();
ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
shapeDrawable.getPaint().setColor(Color.WHITE);
shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
shapeDrawable.getPaint().setAntiAlias(true);
shapeDrawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
return shapeDrawable.mutate();
}

最后在你的按钮中你可以这样设置,

Button button = (Button) findViewById(R.id.button);

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
button.setBackgroundDrawable(getMyDrawable());
} else {
button.setBackground(getMyDrawable());
}

关于java - 以编程方式向按钮添加描边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45180032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com