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 に答える