我试图在按下按钮时向按钮添加边框(笔划),然后在按下另一个按钮时删除笔划。问题是按钮保持按钮+笔划的大小而不是回到原始大小(没有笔划)
我的尝试代码如下所示:
front.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
ShapeDrawable shapeDrawable = new ShapeDrawable();
shapeDrawable.getPaint().setColor(Color.RED);
shapeDrawable.getPaint().setStrokeWidth(30f);
shapeDrawable.getPaint().setStyle(Paint.Style.STROKE);
front.setBackgroundDrawable(shapeDrawable);
return false;
}
});
back.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
ShapeDrawable shapeDrawable = new ShapeDrawable();
shapeDrawable.getPaint().setColor(Color.GRAY);
shapeDrawable.getPaint().setStrokeWidth(0f);
shapeDrawable.getPaint().setStyle(Paint.Style.STROKE);
front.setBackgroundDrawable(shapeDrawable);
return false;
}
});
答案 0 :(得分:0)
尝试将另一个按钮的背景drawable设置为null。另外,请注意你在第二种方法中犯了错误 - 你有front.setBackgroundDrawable(shapeDrawable);
而不是back.setBackgroundDrawable(shapeDrawable);
。您使用的工作代码:
front.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
ShapeDrawable shapeDrawable = new ShapeDrawable();
shapeDrawable.getPaint().setColor(Color.RED);
shapeDrawable.getPaint().setStrokeWidth(30f);
shapeDrawable.getPaint().setStyle(Paint.Style.STROKE);
front.setBackgroundDrawable(shapeDrawable);
back.setBackgroundDrawable(null);
return false;
}
});
back.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
ShapeDrawable shapeDrawable = new ShapeDrawable();
shapeDrawable.getPaint().setColor(Color.GRAY);
shapeDrawable.getPaint().setStrokeWidth(0f);
shapeDrawable.getPaint().setStyle(Paint.Style.STROKE);
back.setBackgroundDrawable(shapeDrawable);
front.setBackgroundDrawable(null);
return false;
}
});
答案 1 :(得分:0)
我找到解决此问题的最佳方法是将背景颜色设置为所需的颜色,而不是将drawable null设置为。对于我上面的代码示例,我将以下代码恢复为灰色按钮:
front.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
ShapeDrawable shapeDrawable = new ShapeDrawable();
shapeDrawable.getPaint().setColor(Color.RED);
shapeDrawable.getPaint().setStrokeWidth(30f);
shapeDrawable.getPaint().setStyle(Paint.Style.STROKE);
front.setBackgroundDrawable(shapeDrawable);
back.setBackgroundColor(Color.GRAY);
return false;
}
});
back.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
ShapeDrawable shapeDrawable = new ShapeDrawable();
shapeDrawable.getPaint().setColor(Color.GRAY);
shapeDrawable.getPaint().setStrokeWidth(0f);
shapeDrawable.getPaint().setStyle(Paint.Style.STROKE);
back.setBackgroundDrawable(shapeDrawable);
front.setBackgroundColor(Color.GRAY);
return false;
}
});