actionSearch Edittex 上的数据绑定

Are*_*ref 2 android kotlin android-databinding

如何在kotlin中绑定点击actionSearch软键盘按钮的数据@BindingAdapter

我的编辑文本:

<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"/>
Run Code Online (Sandbox Code Playgroud)

我的视图模型:

class RelationListViewModel: BaseViewModel(){
   //..    
    val text: MutableLiveData<String> = MutableLiveData()
Run Code Online (Sandbox Code Playgroud)

mah*_*azi 5

添加一个BindingAdaptersetOnEditorActionListener


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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并在您的 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}"/>
Run Code Online (Sandbox Code Playgroud)