148

如何在 Kotlin 中为 EditText addTextChangeListener 构建 lambda 表达式?下面给出一个错误:

passwordEditText.addTextChangedListener { charSequence  ->
    try {
        password = charSequence.toString()
    } catch (error: Throwable) {
        raise(error)
    }
}
4

12 回答 12

329

addTextChangedListener()接受一个TextWatcher带有 3 个方法的接口。您所写的内容只有TextWatcher在只有一种方法时才有效。我猜你得到的错误与你的 lambda 没有实现其他两种方法有关。您有 2 个选择。

  1. 抛弃 lambda,只使用匿名内部类
    editText.addTextChangedListener(object : TextWatcher {
      override fun afterTextChanged(s: Editable?) {
      }
    
      override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
      }
    
      override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
      }
    })
  1. 创建一个扩展方法,以便您可以使用 lambda 表达式:
    fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
        this.addTextChangedListener(object : TextWatcher {
          override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
          }
    
          override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
          }
    
          override fun afterTextChanged(editable: Editable?) {
            afterTextChanged.invoke(editable.toString())
          }
        })
    }

然后像这样使用扩展名:

editText.afterTextChanged { doSomethingWithText(it) }
于 2016-11-13T01:57:19.583 回答
79

添加这个核心ktx依赖

implementation 'androidx.core:core-ktx:1.0.0'

你只需要做

passwordEditText.doAfterTextChanged{ }

于 2019-10-03T10:16:56.517 回答
30

有点老了,但是使用 Kotlin Android 扩展你可以做这样的事情:

editTextRequest.textChangedListener {
            afterTextChanged {
                // Do something here...
            }
}

不需要额外的代码,只需添加:

implementation 'androidx.core:core-ktx:1.0.0'
于 2018-05-24T08:42:22.967 回答
14

希望此Kotlin示例有助于说明清楚:

class MainFragment : Fragment() {

    private lateinit var viewModel: MainViewModel

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View {
    val view = inflater.inflate(R.layout.main_fragment, container, false)

    view.user.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable) {
                userLayout.error =
                        if (s.length > userLayout.counterMaxLength) {
                            "Max character length is: ${userLayout.counterMaxLength}"
                        } else null
        }
    })
    return view
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
    // TODO: Use the ViewModel
   }
}

使用此XML布局:

<android.support.design.widget.TextInputLayout
    android:id="@+id/userLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:counterMaxLength="5"
    app:counterEnabled="true"
    android:hint="user_name">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>

Gradle

android {
    compileSdkVersion 'android-P'
...
}
    api 'com.android.support:design:28.0.0-alpha1'

    implementation 'com.android.support:appcompat-v7:28.0.0-alpha1' // appcompat library
于 2018-06-01T22:18:05.910 回答
14

测试它:

passwordEditText.addTextChangedListener(object:TextWatcher{
    override fun afterTextChanged(s: Editable?) { }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
})
于 2019-05-22T13:39:12.147 回答
13

对不起,来晚了!

如果您添加implementation 'androidx.core:core-ktx:1.1.0'到模块的 build.gradle 文件中,那么您可以使用

etPlayer1.doOnTextChanged { text, start, count, after -> // Do stuff }
于 2020-02-19T09:16:01.840 回答
12

如果你使用implementation 'androidx.core:core-ktx:1.1.0-alpha05'你可以使用

For android.widget.TextView
TextWatcher 
TextView.doBeforeTextChanged(crossinline action: (text: CharSequence?, start: Int, count: Int, after: Int) -> Unit)
Add an action which will be invoked before the text changed.

TextWatcher 
TextView.doOnTextChanged(crossinline action: (text: CharSequence?, start: Int, count: Int, after: Int) -> Unit)
Add an action which will be invoked when the text is changing.

TextWatcher 
TextView.doAfterTextChanged(crossinline action: (text: Editable?) -> Unit)

https://developer.android.com/reference/kotlin/androidx/core/widget/package-summary#extension-functions

于 2019-04-04T19:57:28.400 回答
7

添加核心ktx依赖

implementation 'androidx.core:core-ktx:1.3.0'

你可以像这样简单地实现

    edit_text.addTextChangedListener { it: Editable? ->
      // Do your stuff here
    }
于 2020-06-08T04:34:37.580 回答
7

如果您使用 Material Filled text fieldOutlined text field,请尝试分别响应文档中提到的输入文本更改:

filledTextField.editText?.doOnTextChanged { inputText, _, _, _ ->
    // Respond to input text change
}

outlinedTextField.editText?.doOnTextChanged { inputText, _, _, _ ->
    // Respond to input text change
}
于 2021-02-21T17:29:53.843 回答
3

另一种选择是KAndroid图书馆 -

implementation 'com.pawegio.kandroid:kandroid:0.8.7@aar'

然后你可以做这样的事情......

editText.textWatcher { afterTextChanged { doSomething() } }

显然,使用整个库来解决您的问题是多余的,但它还附带了一系列其他有用的扩展,这些扩展消除了 Android SDK 中的样板代码。

于 2017-08-24T08:05:30.940 回答
3

您可以使用 kotlin 的命名参数:

private val beforeTextChangedStub: (CharSequence, Int, Int, Int) -> Unit = { _, _, _, _ -> }
private val onTextChangedStub: (CharSequence, Int, Int, Int) -> Unit = { _, _, _, _ -> }
private val afterTextChangedStub: (Editable) -> Unit = {}

fun EditText.addChangedListener(
        beforeTextChanged: (CharSequence, Int, Int, Int) -> Unit = beforeTextChangedStub,
        onTextChanged: (CharSequence, Int, Int, Int) -> Unit = onTextChangedStub,
        afterTextChanged: (Editable) -> Unit = afterTextChangedStub
) = addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
        beforeTextChanged(charSequence, i, i1, i2)
    }

    override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
        onTextChanged(charSequence, i, i1, i2)
    }

    override fun afterTextChanged(editable: Editable) {
        afterTextChanged(editable)
    }
})
于 2019-04-05T12:06:35.663 回答
-10

这看起来很整洁:

passwordEditText.setOnEditorActionListener { 
    textView, keyCode, keyEvent ->
    val DONE = 6

    if (keyCode == DONE) {                       
         // your code here
    }
    false
}
于 2016-11-13T02:16:29.300 回答