Привязка данных на actionSearch Edittex - PullRequest
1 голос
/ 17 мая 2019

Как связать данные при нажатии кнопки actionSearch на мягкой клавиатуре с @BindingAdapter в котлине?

Мой editText:

<android.support.v7.widget.AppCompatEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:padding="10dp"
        android:text="@{viewModel.text}"
        android:hint="@string/edit_text_hint"
        android:imeOptions="actionSearch"/>

Моя модель представления:

class RelationListViewModel: BaseViewModel(){
   //..    
    val text: MutableLiveData<String> = MutableLiveData()

1 Ответ

1 голос
/ 17 мая 2019

Добавить BindingAdapter для setOnEditorActionListener


class ViewModel {
    private val editorActionListener: TextView.OnEditorActionListener

    init {
        this.editorActionListener = TextView.OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // do your search logic
                true
            } else false
        }
    }

    companion object {

        @BindingAdapter("onEditorActionListener")
        fun bindOnEditorActionListener(editText: EditText, editorActionListener: TextView.OnEditorActionListener) {
            editText.setOnEditorActionListener(editorActionListener)
        }
    }
}

и используйте его в своем xml

<android.support.v7.widget.AppCompatEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:padding="10dp"
        android:text="@{viewModel.text}"
        android:hint="@string/edit_text_hint"
        android:imeOptions="actionSearch"
        app:onEditorActionListener="@{viewModel.editorActionListener}"/>
...