i want to show a custom popup menu when user click on a floating icon
the float icon create with an service and i have no activity
this is my floating icon c
I was getting this error while trying to show DatePicker
from Fragment
.
I changed
val datePickerDialog = DatePickerDialog(activity!!.applicationContext, ...)
to
val datePickerDialog = DatePickerDialog(requireContext(), ...)
and it worked just fine.
You need to pass your activity in the constructor
PopupWindow popupWindow = new PopupWindow(YourActivity.this)
PopupWindow
can only be attached to an Activity
. In your case you are trying to add PopupWindow
to service
which is not right.
To solve this problem you can use a blank and transparent Activity
. On click of floating icon, launch the Activity
and on onCreate
of Activity
show the PopupWindow
.
On dismiss of PopupWindow
, you can finish
the transparent Activity
.
Hope this helps you.
You should not put the windowManager.addView in onCreate
Try to call the windowManager.addView
after onWindowFocusChanged
and the status of hasFoucus
is true.
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
//code here
//that you can add a flag that you can call windowManager.addView now.
}
This error happens when you are trying to show popUpWindow too early ,to fix it, give Id to main layout as main_layout
and use below code
Java:
findViewById(R.id.main_layout).post(new Runnable() {
public void run() {
popupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
}
});
Kotlin:
main_layout.post {
popupWindow?.showAtLocation(main_layout, Gravity.CENTER, 0, 0)
}
Credit to @kordzik
If you're using getApplicationContext()
as Context
in Activity for the dialog like this
Dialog dialog = new Dialog(getApplicationContext());
then use YourActivityName.this
Dialog dialog = new Dialog(YourActivityName.this);