You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在从SharedPreferences填充EditText时触发onTextChanged事件

问题原因

触发回调失败的核心原因是代码执行顺序错误:调用setText()填充历史内容时,还未给EditText绑定TextWatcher监听器,自然收不到变更回调。你当前的执行顺序为:

  1. 加载布局得到binding实例
  2. 直接给EditText设置历史输入内容
  3. 后续才执行绑定TextWatcher的逻辑

解决方案

方案1:调整执行顺序(推荐)

保证先完成TextWatcher的绑定,再调用setText()填充内容,修改后的代码示例如下:

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentCitySearchBinding.inflate(inflater)

        // 先绑定TextWatcher监听器
        binding.etCitySearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                text: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
                handler.removeCallbacksAndMessages(null)
                if (text?.isNotEmpty() == true) {
                    val searchCity = Runnable {
                        viewModel.getWeatherByCityName(requireContext(), text.toString())
                    }
                    handler.postDelayed(searchCity, DELAY)
                }
            }

            override fun afterTextChanged(text: Editable?) {
            }
        })

        // 监听器绑定完成后再填充历史内容
        binding.etCitySearch.apply {
            setText(viewModel.getUserInput)
            setSelection(length())
        }

        return binding.root
    }

方案2:手动触发兜底

如果调整顺序后仍不触发(比如setText的内容和EditText原有内容完全一致时系统不会触发回调),可以在设置内容后手动调用一次查询逻辑:

binding.etCitySearch.apply {
    val historyInput = viewModel.getUserInput
    setText(historyInput)
    setSelection(length())
    // 手动触发查询逻辑,和监听器内逻辑对齐
    if (historyInput.isNotEmpty()) {
        handler.removeCallbacksAndMessages(null)
        val searchCity = Runnable {
            viewModel.getWeatherByCityName(requireContext(), historyInput)
        }
        handler.postDelayed(searchCity, DELAY)
    }
}

内容的提问来源于stack exchange,提问作者SoulReaver313

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:57:02