Android - 以编程方式设置背景选择器状态

时间:2014-03-09 23:21:39

标签: android android-selector android-background

我有一个包含EditText和ImageView的线性布局。我给了EditText一个@null背景,并给了LinearLayout一个背景:

?android:attr/editTextBackground

让整个东西看起来像是一个小部件。当EditText获得焦点/被选中时,我想更新线性布局的背景可绘制,以显示整个事物被选中。

我的线性布局布局XML:

<LinearLayout
    android:id="@+id/search_plate"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/editTextBackground">

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/edit_text"
        android:layout_weight="1"
        android:background="@null"
        android:height="36dp"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/image_view_close"
        android:src="@drawable/ic_clear"
        android:focusable="true"
        android:background="?android:attr/selectableItemBackground"/>
</LinearLayout>

这是我在编辑EditText时尝试更改LinearLayout的背景状态的代码:

public class IconEditText extends LinearLayout implements View.OnFocusChangeListener {

    private static final String LOG_TAG = "IconEditText";

    private View mSearchPlate;            // Linear Layout
    private EditText mEditTextSearch;

    public IconEditText(Context context) {
        this(context, null);
    }

    public IconEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.icon_edit_text, this, true);

        mSearchPlate = findViewById(R.id.search_plate);
        mEditTextSearch = (EditText) findViewById(R.id.editText);

        mEditTextSearch.setOnFocusChangeListener(this);

    }

    @Override
    public void onFocusChange(View view, boolean focused) {
        mSearchPlate.getBackground().setState(focused ? FOCUSED_STATE_SET : EMPTY_STATE_SET);
    }
}

除了使用FOCUSED_STATE_SET之外,我还尝试了以下方法:

ENABLED_FOCUSED_SELECTED_STATE_SET
FOCUSED_SELECTED_STATE_SET
ENABLED_SELECTED_STATE_SET
SELECTED_STATE_SET

上述所有内容似乎都没有将LinearLayout的背景更改为蓝色下划线。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

似乎好像:ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET有效......如果有人能解释一下,那就太好了!