将按钮更改为以编程方式舍入

Change a button to round programmatically

在 xml 中有一个圆形按钮,我想在单击它时更改它的颜色。我用这段代码做了,但它又变成了方形,而不是原来的圆形:

button1.setBackgroundColor(Color.BLUE);

有谁知道我也可以更改按钮的形状吗?

GradientDrawable shape =  new GradientDrawable();
 shape.setCornerRadius( 8 );

 // add some color
 // You can add your random color generator here
 // and set color
 if (i % 2 == 0) {
  shape.setColor(Color.RED);
 } else {
  shape.setColor(Color.BLUE);
 }

 // now find your view and add background to it
 findViewById( R.id.my_view ).setBackground(shape);