如何为Android Studio中PopupWindow弹窗内的按钮设置setOnClickListener?
Android弹窗按钮点击事件设置解决方案
问题根因
onCreate执行阶段,弹窗布局confirm_number_popup尚未被加载,直接调用Activity自带的findViewById()查找弹窗内的控件会返回null,后续调用setOnClickListener()触发空指针异常,就是你遇到的应用停止响应问题。
修复代码
你需要在弹窗布局完成inflate后,通过inflate返回的popupView对象查找弹窗内的按钮,再绑定点击事件,修改后的代码如下:
public void onButtonShowPopupWindowClick(View view) { // inflate the layout of the popup window LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View popupView = inflater.inflate(R.layout.confirm_number_popup, null); hideSoftKeyboard(Register.this); // 在这里绑定弹窗内按钮的点击事件 Button btnEdit = popupView.findViewById(R.id.btn_edit); Button btnOk = popupView.findViewById(R.id.btn_Ok); btnEdit.setOnClickListener(v -> { // 编写edit按钮的逻辑 popupWindow.dismiss(); // 可选:点击后关闭弹窗 }); btnOk.setOnClickListener(v -> { // 编写ok按钮的逻辑 popupWindow.dismiss(); // 可选:点击后关闭弹窗 }); // create the popup window int width = LinearLayout.LayoutParams.WRAP_CONTENT; int height = LinearLayout.LayoutParams.WRAP_CONTENT; boolean focusable = true; // lets taps outside the popup also dismiss it final PopupWindow popupWindow = new PopupWindow(popupView, width, height, false); // show the popup window // which view you pass in doesn't matter, it is only used for the window token popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0); // dismiss the popup window when touched popupView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { popupWindow.dismiss(); return true; } }); }
注意点
- 查找弹窗内控件必须调用弹窗根布局的
findViewById()方法,不能用Activity的findViewById() - 点击事件绑定逻辑要放在
inflate布局之后,showAtLocation之前或之后都可以,只要保证是在布局加载完成后执行即可。
内容的提问来源于stack exchange,提问作者Shaurya Goyal
相关产品推荐
相关产品推荐

