获取android中按钮的背景颜色

Los*_*ppy 38 android button background-color

如何获得按钮的背景颜色.在xml我使用---- android:background = XXXXX现在在活动类中设置背景颜色如何检索它具有的这个值?

Mat*_*udy 81

不幸的是我不知道如何检索实际的颜色.

很容易得到这个 Drawable

Button button = (Button) findViewById(R.id.my_button);
Drawable buttonBackground = button.getBackground();
Run Code Online (Sandbox Code Playgroud)

如果您知道这是一种颜色,那么您可以尝试

ColorDrawable buttonColor = (ColorDrawable) button.getBackground();
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Android 3.0+,则可以获得颜色的资源ID.

int colorId = buttonColor.getColor();
Run Code Online (Sandbox Code Playgroud)

并将其与您指定的颜色进行比较,即.

if (colorID == R.color.green) {
  log("color is green");
}
Run Code Online (Sandbox Code Playgroud)

  • 你确定getColor()得到了id吗?我认为它获得了颜色的实际int值(即0xAARRGGBB).我用"#00000001"进行了测试,然后返回1. (2认同)
  • 我使用这个 `((ColorDrawable) row.getBackground()).getColor()` 作为 `(row.background as ColorDrawable).color` 但我遇到了这个错误 `android.graphics.drawable.StateListDrawable 无法转换为 android .graphics.drawable.ColorDrawable` (2认同)

jpm*_*sta 20

private Bitmap mBitmap;
private Canvas mCanvas;
private Rect mBounds;

public void initIfNeeded() {
  if(mBitmap == null) {
    mBitmap = Bitmap.createBitmap(1,1, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
    mBounds = new Rect();
  }
}

public int getBackgroundColor(View view) {
  // The actual color, not the id.
  int color = Color.BLACK;

  if(view.getBackground() instanceof ColorDrawable) {
    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
      initIfNeeded();

      // If the ColorDrawable makes use of its bounds in the draw method,
      // we may not be able to get the color we want. This is not the usual
      // case before Ice Cream Sandwich (4.0.1 r1).
      // Yet, we change the bounds temporarily, just to be sure that we are
      // successful.
      ColorDrawable colorDrawable = (ColorDrawable)view.getBackground();

      mBounds.set(colorDrawable.getBounds()); // Save the original bounds.
      colorDrawable.setBounds(0, 0, 1, 1); // Change the bounds.

      colorDrawable.draw(mCanvas);
      color = mBitmap.getPixel(0, 0);

      colorDrawable.setBounds(mBounds); // Restore the original bounds.
    }
    else {
      color = ((ColorDrawable)view.getBackground()).getColor();
    }
  }

  return color;
}
Run Code Online (Sandbox Code Playgroud)


ble*_*enm 14

您也可以尝试将颜色值设置为标记之类的内容

android:tag="#ff0000"
Run Code Online (Sandbox Code Playgroud)

并从代码中访问它

String colorCode = (String)btn.getTag();
Run Code Online (Sandbox Code Playgroud)


小智 5

获取颜色的最简单方法是:

int color = ((ColorDrawable)button.getBackground()).getColor();
Run Code Online (Sandbox Code Playgroud)

测试并使用Lollipop 5.1.1