繁体   English   中英

在 Android Studio 中使用 Kotlin 输入文本时,如何更改 EditText 的背景颜色?

[英]How can I change the background color of an EditText when text is entered using Kotlin in Android Studio?

为了清楚起见,我想在输入文本后将 textField 的颜色更改为清晰,并使其恢复为旧颜色,在我的情况下,当它没有文本时为灰色。 我查看了 stackoverflow 并找到了一些答案,但它是用 Java 编写的,我仍然是 Kotlin 的初学者,但我正在用 Kotlin 编写它以用于我的工作。

本质上,我想知道输入文本后如何更改 textField 的背景?

在此处输入图片说明

一旦使用 Kotlin 输入文本,我想改变它的背景颜色。

这是我所指的 XML EditText:

  <EditText
    android:id="@+id/description"
    android:layout_width="350dp"
    android:layout_height="200dp"
    android:layout_below="@id/addImage"
    android:layout_alignBottom="@id/addImage"
    android:layout_marginStart="50dp"
    android:layout_marginTop="125dp"
    android:layout_marginEnd="50dp"
    android:layout_marginBottom="75dp"
    android:background="@color/lightGray"
    android:gravity="center"
    android:hint="@string/description"
    android:inputType="text"
    app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

我现在该去哪里?

class PostActivity : AppCompatActivity() {
    private lateinit var button: Button
    private lateinit var imageView: ImageView
    private lateinit var editText: EditText


override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_post)

    editText = findViewById(R.id.description)

}
}

这就是我在我的活动中所拥有的。 我没有任何关于如何做到这一点的方法。

添加 TextWatcher 以在文本更改时做出反应。

val originalColor = editText.backgroundColor
val haveTextColor = Color.TRANSPARENT // or whatever you want
editText.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) {
            editText.setBackgroundColor(if (s.isEmpty()) originalColor else haveTextColor)
        }

    })

您可以在此处使用doAfterTextChanged Kotlin 扩展功能。 它可用于在每次文本更改时执行某些操作。

editText.doAfterTextChanged { text ->
    editText.setBackgroundColor(if (text.isEmpty()) color1 else color2) // Choose whatever colors you want
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM