获取android中button的背景颜色

我如何获得一个button的背景颜色。 在xml中,我现在在活动类中使用—- android:background = XXXXX设置背景颜色,我如何检索它具有的值?

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

把它作为Drawable很容易

 Button button = (Button) findViewById(R.id.my_button); Drawable buttonBackground = button.getBackground(); 

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

 ColorDrawable buttonColor = (ColorDrawable) button.getBackground(); 

如果您使用的是Android 3.0以上版本,则可以获取该颜色的资源ID。

 int colorId = buttonColor.getColor(); 

并比较这与你指定的颜色,即。

 if (colorID == R.color.green) { log("color is green"); } 
 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; } 

你也可以尝试像设置颜色值的标签

 android:tag="#ff0000" 

并从代码中访问它

 String colorCode = (String)btn.getTag(); 

最简单的方法来获得我的颜色是:

 int color = ((ColorDrawable)button.getBackground()).getColor(); 

testing和工作棒棒糖5.1.1

为了得到Drawable的背景,你使用

 public Drawable getBackground(); 

如在基本View类中定义的。

不要忘了Button可以有一个图像,一个颜色,一个渐变的背景。 如果你使用android:background =“#ffffff”,背景的类将是

android.graphics.drawable.ColorDrawable

从那里你可以打电话

 public int getColor() 

尝试这个:

 list_view.getChildAt(position).setBackgroundColor(Color.YELLOW); ColorDrawable corItem = (ColorDrawable) list_view.getChildAt(position).getBackground(); if(corItem.getColor() == Color.YELLOW){ Toast.makeText(NovoProcessoActivity.this,"Right Color!", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(NovoProcessoActivity.this,"Wrong Color!", Toast.LENGTH_SHORT).show(); } 

要么

 int color =( (ColorDrawable) list_view.getChildAt(position).getBackground()).getColor();