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

如何修改自定义Dialog Box中TextView的文本,赋值不生效怎么解决?

问题原因

你在查找body_message控件时使用了Activity的全局findViewById方法,但该控件属于你单独为Dialog加载的布局dialogView中,全局查找无法匹配到Dialog布局内的控件,所以赋值操作实际没有作用在正确的控件上。

修正方案

只需要修改查找body_message的调用对象,改为从dialogView中查找即可,修正后的核心代码如下:

findViewById<View>(R.id.customDialog).setOnClickListener { v ->
    val builder: AlertDialog.Builder = AlertDialog.Builder(this@MainActivity, R.style.CustomAlertDialog)
    val viewGroup = findViewById<ViewGroup>(android.R.id.content)
    val dialogView: View = LayoutInflater.from(v.context).inflate(R.layout.custom_dialog, viewGroup, false)
    val buttonOk = dialogView.findViewById<Button>(R.id.buttonOk)
    // 改为从dialogView中查找目标TextView
    val body_message = dialogView.findViewById<TextView>(R.id.body_message)

    body_message.text = message

    builder.setView(dialogView)
    val alertDialog: AlertDialog = builder.create()
    buttonOk.setOnClickListener { alertDialog.dismiss() }
    alertDialog.show()
}

可选优化

你可以封装一个弹出自定义Dialog的公共方法,支持外部传入自定义消息,方便不同业务场景调用:

private fun showCustomDialog(message: String) {
    val builder = AlertDialog.Builder(this@MainActivity, R.style.CustomAlertDialog)
    val dialogView = LayoutInflater.from(this).inflate(R.layout.custom_dialog, null)
    dialogView.findViewById<TextView>(R.id.body_message).text = message
    builder.setView(dialogView)
    val alertDialog = builder.create()
    dialogView.findViewById<Button>(R.id.buttonOk).setOnClickListener {
        alertDialog.dismiss()
    }
    alertDialog.show()
}

调用时直接传入对应消息即可:showCustomDialog("测试消息")


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:24:01