在actionSearch Edittex上进行数据绑定

时间:2019-05-16 21:19:44

标签: android kotlin android-databinding

如何在Kotlin中用df.style.applymap() 单击软键盘的actionSearch按钮来绑定数据?

我的editText:

@BindingAdapter

我的viewModel:

<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"/>

2 个答案:

答案 0 :(得分:1)

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}"/>

答案 1 :(得分:0)

onEditoractionListener 的数据绑定可以实现为

fun onEditorAction(view: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            //todo action you want on this
            return true
        }
        return false
    }

并在布局文件中用作

 android:onEditorAction="@{(view,actionId,event) -> viewmodel.onEditorAction(view,actionId,event)}"