Reputation: 651
I'm trying to implement popup view into my app with bottom navigation (I'm using fragments for every item in navigation). In one fragment I have ListView
with items. Each Item has button in it and I want to create popup view that tells further info about its item.
I have tried creating popups in separate apps on activities and it worked just fine, therefore I assume this is problem of slightly complicated structure of my app. (Activity - fragment - listView - Item - button that summons popup)
Here is my code:
Fragment:
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);
}
Adapter:
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;
}
When I click the button in listView, app prints both Log.d(TAG, "onClick: button");
and Log.d(TAG, "setPopupLayout");
.
Then NullPointerExeption
is thrown:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.getRootView()' on a null object reference
and this line gets highlited:
popupWindow.showAtLocation(popupLayout, Gravity.NO_GRAVITY ,400, 400);
I'm still new to android and I will be so thankful for any piece of advice! Thanks for reading
EDIT:
I think I found the issue, in
popupWindow.showAtLocation(popupLayout, Gravity.NO_GRAVITY ,400, 400);
I use popupLayout
which is assigned in onViewCreated
as
popupLayout = (RelativeLayout) view.findViewById(R.id.relative);
and this is assigned as null (which seems to be causing the error).
Upvotes: 1
Views: 236
Reputation: 651
replace popupWindow.showAtLocation(popupLayout, Gravity.NO_GRAVITY ,400, 400);
by popupWindow.showAtLocation(getView(), Gravity.NO_GRAVITY ,400, 400);
Upvotes: 1
Reputation: 883
Try something like this
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);
Upvotes: 0