Kotlin addTextChangeListener lambda?

Как вы создаете лямбда-выражение для EditText addTextChangeListener в Котлине? Ниже приведена ошибка:

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

Ответы

Ответ 1

Это выглядит аккуратно:

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

    if (keyCode == DONE) {                       
         // your code here
    }
    false
}

Ответ 2

addTextChangedListener() принимает TextWatcher, который представляет собой интерфейс с тремя методами. То, что вы написали, будет работать только в том случае, если TextWatcher имеет только 1 метод. Я собираюсь угадать, что ошибка, которую вы получаете, связана с вашей лямбдой, не реализующей другие 2 метода. У вас есть 2 варианта в будущем.

1) Поймайте лямбда и просто используйте анонимный внутренний класс

editText.addTextChangedListener(object : TextWatcher {
  override fun afterTextChanged(p0: Editable?) {
  }

  override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
  }

  override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
  }
})

2) Создайте метод расширения, чтобы вы могли использовать выражение лямбда:

fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
      override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
      }

      override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
      }

      override fun afterTextChanged(editable: Editable?) {
        afterTextChanged.invoke(editable.toString())
      }
    })
}

И затем используйте расширение следующим образом:

editText.afterTextChanged { doSomethingWithText(it) }

Ответ 3

надеюсь, что этот образец 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

Ответ 4

Немного устаревший, но используя расширения Kotlin для Android, вы можете сделать что-то вроде этого:

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

Никакого дополнительного кода не требуется, просто добавьте:

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

Ответ 5

если вы используете 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

Ответ 6

Попробуй это:

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) {

    }

})

Ответ 7

Другой альтернативой является библиотека KAndroid -

implementation 'com.pawegio.kandroid:kandroid:[email protected]'

Тогда вы могли бы сделать что-то вроде этого...

editText.textWatcher { afterTextChanged { doSomething() } }

Очевидно, что чрезмерно использовать целую библиотеку для решения вашей проблемы, но она также поставляется с целым рядом других полезных расширений, которые устраняют шаблонный код в Android SDK.

Ответ 8

Вы можете использовать именованные параметры 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)
    }
})

Ответ 9

Вы просто должны сделать

passwordEditText.doAfterTextChanged{ }