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

Android待办应用AlertDialog自定义布局EditText输入值无法获取显示问题

问题原因

你在AlertDialog确认按钮的回调逻辑里犯了视图查找的基础错误:

  • 你提前加载了弹窗布局alertView并设置给了AlertDialog,用户所有的输入内容都存储在这个alertView实例下的EditText控件中
  • 但你在点击确认按钮时,重新 inflate 了一个全新的add_daily布局实例addItemView,这个新实例完全没有经过用户输入,内部的EditText自然是空值,和你添加MaterialCardView没有任何关联
修复代码

修改ShowTaskDialog方法的逻辑,直接从弹窗绑定的alertView中获取输入内容即可:

public void ShowTaskDialog(Context c){
    AlertDialog.Builder alert = new AlertDialog.Builder(c);
    // 这个alertView才是弹窗实际显示的布局实例
    View alertView = getLayoutInflater().inflate(R.layout.add_daily, null);

    alert.setView(alertView);
    alert.setPositiveButton("Post", (dialog, which) -> {
        LinearLayout taskView = findViewById(R.id.taskArea);
        // 去掉重复inflate add_daily的错误代码,直接从alertView找输入控件
        EditText textView = alertView.findViewById(R.id.txtTaskName);
        String taskName = textView.getText().toString().trim();

        View task_View = getLayoutInflater().inflate(R.layout.item_list, null);
        TextView txtName = task_View.findViewById(R.id.txtName);
        txtName.setText(taskName);
        taskView.addView(task_View);
    });
    alert.setNegativeButton("Cancel", (dialog, which) -> {
        //Close Alert
    });
    alertDialog = alert.show();
    alertDialog.setCanceledOnTouchOutside(false);
    alertDialog.setCancelable(false);
    alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
}
补充优化建议
  • 你当前的add_daily布局里,第一个子LinearLayout下的ImageView宽高设置为match_parent,会挤占EditText的输入区域,建议修改为固定宽高,避免EditText输入内容被遮挡
  • 获取输入内容后建议调用trim()去除首尾空白字符,避免用户输入全空格的无效内容

内容的提问来源于stack exchange,提问作者PureWare -Legends Of Gaming

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:27:00