从片段的Lis​​tView中的按钮创建PopupView

时间:2019-01-13 21:07:58

标签: java android popupwindow

我正在尝试通过底部导航在我的应用中实现弹出视图(我在导航中的每个项目都使用片段)。在一个片段中,我有ListView个项目。每个项目都有一个按钮,我想创建一个弹出视图,以告知有关该项目的更多信息。

我尝试在活动的单独应用中创建弹出窗口,但效果很好,因此我认为这是我的应用结构稍微复杂的问题。 (活动-片段-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(这似乎是导致错误的原因)。

2 个答案:

答案 0 :(得分:0)

尝试这样的事情

Fragment.class

View popupView =  layoutInflater.inflate(R.layout.popup_compressors, null);
final PopupWindow popupWindow = new PopupWindow(popupView, 500, 500);

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

答案 1 :(得分:0)

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

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