Android Studio中如何在PopupWindow中使用setText()方法?EditText内容无法传递至弹窗的问题求助
解决PopupWindow中TextView空指针并传递EditText内容的问题
兄弟,你的空指针问题其实很好解决——你找错控件的上下文了!
你直接调用findViewById(R.id.txt_phone_number_confirm),这是在Activity的布局里找控件,但这个TextView明明是属于弹窗的confirm_number_popup.xml布局的,Activity根本找不到它,自然返回null,调用setText()就触发异常了。
正确的做法是:通过你inflate出来的弹窗根视图popupView来查找弹窗里的所有控件,因为这些控件都是popupView的子元素。
下面是修改后的完整代码,我给你标清楚关键改动:
public void onButtonShowPopupWindowClick(View view) { // 1. 获取LayoutInflater并加载弹窗布局 LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); @SuppressLint("InflateParams") View popupView = inflater.inflate(R.layout.confirm_number_popup, null); // --- 关键改动在这里 --- // 2. 通过popupView查找弹窗内的TextView,而不是用Activity的findViewById TextView txt_phone_confirm = popupView.findViewById(R.id.txt_phone_number_confirm); // 3. 获取Activity中EditText的内容 EditText txt_Phone = findViewById(R.id.Phone_Number); // 4. 安全地设置文本(可以加个判空避免意外) if (txt_Phone.getText() != null) { txt_phone_confirm.setText(txt_Phone.getText().toString()); } // --- 关键改动结束 --- // 你原来的弹窗初始化逻辑 Button btn1 = popupView.findViewById(R.id.btn_edit); // 这里你其实已经在popupView找按钮了,怎么TextView就忘了呢😉 int width = LinearLayout.LayoutParams.WRAP_CONTENT; int height = LinearLayout.LayoutParams.WRAP_CONTENT; final PopupWindow popupWindow = new PopupWindow(popupView, width, height, false); popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0); }
再给你划几个重点:
- 所有属于弹窗布局的控件,必须用
popupView.findViewById()来获取,不能直接用Activity的findViewById() - 一定要确保在
inflater.inflate()之后再去查找弹窗控件,不然popupView都还没初始化,同样会空指针 - 额外加个EditText内容的判空,是为了防止用户没输入内容时出现不必要的问题,属于优化项
这样改完之后,就能把EditText里的手机号正确传递到弹窗的TextView里显示了。
内容的提问来源于stack exchange,提问作者Shaurya Goyal
相关产品推荐
相关产品推荐

