【Android】监听PopupWindow上的控件出现nullpointerException

本文详细介绍了在Android开发中遇到PopupWindow与按钮出现NullPointer和UnknownSource异常的问题,并提供了针对性的解决方案,包括设置PopupWindow为全局变量及改进按钮ID查找方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   监听PopupWindow上的控件出现nullpointerException异常,有Unknow Source

如下图所示



这里是有问题的代码

/*
 * 获取popupwindow,并设置弹出位置
*/
 View popupView = getLayoutInflater().inflate(R.layout.popup_window_layout, null);
 // 设置背景为圆角
 popupView.setBackgroundResource(R.layout.rounded_corners_view);
 PopupWindow popupWindow = new PopupWindow(popupView, 200,200);
 popupWindow.setTouchable(true);
 popupWindow.setOutsideTouchable(true);
 popupWindow.setFocusable(true);  
							  
 Button button1 =(Button) findViewById(R.id.popupWindowCanclePoint);  // “取消”键
 Button button2 = (Button) findViewById(R.id.popupWindowRemovePoint);
 Button button2 = (Button) popupView.findViewById(R.id.popupWindowRemovePoint);


问题出现在
PopupWindow popupWindow = new PopupWindow(popupView, 200,200);
和后面获取按钮Id的这几行代码

Button button1 =(Button) findViewById(R.id.popupWindowCanclePoint);  // “取消”键
 Button button2 = (Button) findViewById(R.id.popupWindowRemovePoint);

解决方法


1、这里设置弹出PopupWindow只是我这个项目中的一小部分,是在一个方法中设置。所以,要解决nullpointerException和nuknow Source 这两个问题,亦必须要不popupWindow设置为全局变量;

既将

PopupWindow popupWindow = new PopupWindow(popupView, 200,200);
变为

PopupWindow popupWindow;

````````````(省略中间代码)

popupWindow = new PopupWindow(popupView, 200,200);
2、将
 Button button1 =(Button) findViewById(R.id.popupWindowCanclePoint);  // “取消”键
  Button button2 = (Button) findViewById(R.id.popupWindowRemovePoint);
变为


 Button button1 =(Button) popupView.findViewById(R.id.popupWindowCanclePoint);  // “取消”键
 Button button2 = (Button) popupView.findViewById(R.id.popupWindowRemovePoint);
</pre><pre name="code" class="java">

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值