首页 > 解决方案 > 从片段中 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 (这似乎是导致错误的原因)。

标签: javaandroidpopupwindow

解决方案


代替popupWindow.showAtLocation(popupLayout, Gravity.NO_GRAVITY ,400, 400);

经过popupWindow.showAtLocation(getView(), Gravity.NO_GRAVITY ,400, 400);


推荐阅读