1

我想获取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
4

2 回答 2

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");
于 2012-05-30T03:34:20.103 回答
0

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

于 2012-05-30T03:24:40.027 回答