如何在android上获取EditText的背景颜色

时间:2012-05-30 01:55:17

标签: android android-edittext drawable

我想获得EditText的颜色,我可以通过setBackgroundColor设置它,但是没有getBackgroundColor函数

我发现了这个

EditText edtxt;
edtxt.setBackgroundColor(Color.GREEN);
PaintDrawable drawable;
Log.d(TAG,"1");
drawable = (PaintDrawable)edtxt.getBackground();
if(drawable.getPaint().getColor()==(int)Color.GREEN).........
Log.d(TAG,"2");

但它没有工作和崩溃

05-29 19:20:27.526: E/AndroidRuntime(20255): Caused by: java.lang.ClassCastException: android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.PaintDrawable

2 个答案:

答案 0 :(得分:4)

这适用于API级别11及以上

ColorDrawable drawable = (ColorDrawable)edtxt.getBackground();
if(drawable.getColor()==(int)Color.GREEN)
System.out.println("It's Green");

如果您希望它能够在早期的API上运行,我建议您使用自定义EditText并覆盖setBackgroundColor(int color)方法。

public class NewEditText extends EditText {
private int color;
public NewEditText(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}

public NewEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
}

public NewEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // TODO Auto-generated constructor stub
}   


@Override
public void setBackgroundColor(int color) {
    // TODO Auto-generated method stub
    this.color=color;
    super.setBackgroundColor(color);
}

public int getBackgroundColor() {

    return color;
}
}

现在在布局中使用:

<com.aneesh.mypackage.NewEditText
    android:layout_width="fill_parent"
    android:id="@+id/customview"
    android:layout_height="wrap_content"/>

您的活动代码将更改为

NewEditText custView = (NewEditText)findViewById(R.id.customview);
custView.setBackgroundColor(Color.GREEN);
if(custView.getBackgroundColor()==(int)Color.GREEN)
  System.out.println("It's green");

答案 1 :(得分:0)

如果您在运行时设置颜色,最好保存某种标志(例如布尔值)以了解编辑文本的背景颜色。