如何在EditText存在输入内容时动态修改按钮的backgroundTint颜色
问题原因
你的代码仅在onViewCreated生命周期回调中执行了一次输入状态校验逻辑,未为EditText绑定输入变化监听事件,后续用户输入内容时不会触发校验,因此按钮颜色无法动态更新。
修复方案
为EditText注册TextWatcher监听器,输入内容变化时自动触发按钮样式更新逻辑,修改后的代码参考如下:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) navc = Navigation.findNavController(view) registerObservers() setListeners(view) // 初始化时校验一次初始输入状态 updateButtonStyle() // 为EditText绑定输入变化监听 restaurantEmail.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) { // 输入变化时更新按钮样式 updateButtonStyle() } override fun afterTextChanged(s: Editable?) {} }) } // 原onTextChanged方法调整命名为updateButtonStyle,负责更新按钮样式 private fun updateButtonStyle() { val buttonColor = if (restaurantEmail.editableText.isNotEmpty()) { resources.getColor(R.color.standardOrange, null) } else { println("Testingprint") resources.getColor(R.color.standardGrey, null) } sendHtmlcode.backgroundTintList = ColorStateList.valueOf(buttonColor) }
如果你的项目引入了core-ktx扩展依赖,可以使用更简洁的写法,无需手动实现TextWatcher的三个空方法:
restaurantEmail.doOnTextChanged { _, _, _, _ -> updateButtonStyle() }
*注:resources.getColor(int id, Theme theme)是Android 6.0以上的官方推荐写法,可避免使用已废弃的无参方法警告。
内容的提问来源于stack exchange,提问作者ugur d
相关产品推荐
相关产品推荐

