java - 从片段中 ListView 中的按钮创建 PopupView
问题描述
我正在尝试使用底部导航在我的应用程序中实现弹出视图(我正在为导航中的每个项目使用片段)。在一个片段中,我有ListView
物品。每个项目都有按钮,我想创建弹出视图,以提供有关其项目的更多信息。
我曾尝试在活动的单独应用程序中创建弹出窗口并且效果很好,因此我认为这是我的应用程序结构稍微复杂的问题。(活动 - 片段 - 列表视图 - 项目 - 召唤弹出的按钮)
这是我的代码:
分段:
public class myFragment extends Fragment implements myListAdapter.EventListener {
...
@Override
public void setPopupLayout() {
Log.d(TAG, "setPopupLayout");
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup_compressors, null);
PopupWindow popupWindow = new PopupWindow(popupView, 500, 500, true);
TextView textView = popupView.findViewById(R.id.popup_details);
textView.setText("xd");
// Here the error seems to occur
popupWindow.showAtLocation(popupLayout, Gravity.NO_GRAVITY ,400, 400);
}
适配器:
public class myAdapter extends ArrayAdapter<Compressor>
{
private static final String TAG = "Compressor Adapter";
EventListener myListener;
// (...)
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// (...)
Button button = convertView.findViewById(R.id.comp_details);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: button");
myListener.setPopupLayout();
}
});
return convertView;
}
当我单击 listView 中的按钮时,应用程序会同时打印Log.d(TAG, "onClick: button");
和Log.d(TAG, "setPopupLayout");
. 然后NullPointerExeption
抛出:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.getRootView()' on a null object reference
这条线被突出显示:
popupWindow.showAtLocation(popupLayout, Gravity.NO_GRAVITY ,400, 400);
我还是 android 的新手,我会非常感谢任何建议!谢谢阅读
编辑:
我想我发现了问题,在
popupWindow.showAtLocation(popupLayout, Gravity.NO_GRAVITY ,400, 400);
我使用popupLayout
分配onViewCreated
为
popupLayout = (RelativeLayout) view.findViewById(R.id.relative);
并将其分配为 null (这似乎是导致错误的原因)。
解决方案
代替popupWindow.showAtLocation(popupLayout, Gravity.NO_GRAVITY ,400, 400);
经过popupWindow.showAtLocation(getView(), Gravity.NO_GRAVITY ,400, 400);
推荐阅读
- tomcat8 - 无法在 ubuntu 18.04 上为 https 配置 tomcat 8.5.57 网络服务器
- mongodb - 强制猫鼬默认
- python - 从 sqlite3 获取数据并保存在列表中
- html - 有什么方法可以将引导样式添加到 Django 密码输入字段?
- r - 防止 Rcpp 在 RcppExports.R 中为非导出函数创建包装器
- youtube-data-api - 域更改 YouTube 数据 API v3 不起作用
- javascript - Vue.js 应用程序在 Chrome 中显示正常,但在 Firefox 中显示空白页 - __webpack_require__ 错误
- python - IndentationError: unindent 不匹配任何外部缩进级别 (Elif)
- javascript - Promise 返回 undefined - 在 Promise 中循环
- amazon-web-services - 无法使用 eksctl 创建 AWS EKS 集群