以编程方式设置后台选择器状态



我有一个包含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>

这是我使用的代码,试图改变背景状态的LinearLayout时,EditText的焦点:

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为蓝色下划线的背景。任何帮助将不胜感激!

似乎:ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET工作…如果有人能解释一下,那就太好了!

最新更新