如何从alertDialog.setView加载的自定义布局中获取EditText的值
错误根因
你遇到的报错「无法解析符号 'password_item_dialog'」是以下几个错误共同导致的:
- 未对自定义布局做inflate操作:
R.layout.some_layout是int类型的布局资源标识,不是View实例,你直接用不存在的变量some_layout调用findViewById,自然会报找不到符号的错误。 - 类型强转错误:你将
EditText类型的控件强转为TextView,即使后续成功找到控件,也会抛出类型转换异常。 - 控件获取时机错误:如果直接通过
AlertDialog.Builder.setView(资源ID)的方式设置布局,必须等Dialog实例创建完成后才能获取内部控件,提前调用会返回null。
正确实现方案
推荐使用提前inflate布局的方案,稳定性更高,不会出现获取控件为null的问题:
// 1. 渲染自定义布局得到View实例 View customView = LayoutInflater.from(context).inflate(R.layout.some_layout, null); // 2. 直接从渲染好的View中查找目标控件 EditText titleEt = customView.findViewById(R.id.title); EditText passwordEt = customView.findViewById(R.id.password); // 3. 构建AlertDialog AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); alertDialog.setTitle("Credentials"); alertDialog.setView(customView); // 传入渲染好的View实例 AlertDialog dialog = alertDialog.create(); // 后续可随时获取控件输入值 String username = titleEt.getText().toString(); String password = passwordEt.getText().toString(); dialog.show();
如果不想提前渲染布局,也可以在Dialog创建完成后从Dialog实例中查找控件:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); alertDialog.setTitle("Credentials"); alertDialog.setView(R.layout.some_layout); AlertDialog dialog = alertDialog.create(); dialog.show(); // 必须调用create或show完成Dialog初始化后,才能查找控件 // 从Dialog实例中查找控件 EditText titleEt = dialog.findViewById(R.id.title); EditText passwordEt = dialog.findViewById(R.id.password);
注意:第二种方案必须在Dialog初始化完成后再查找控件,否则会返回null
内容的提问来源于stack exchange,提问作者Ebenezer Isaac
相关产品推荐
相关产品推荐

