I am trying make an android app where clicking a button raises a popupmenu
. The popupmenu
is being generated but not at the correct position. The code is as follows:
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/genderMale"
android:title="Male"
/>
<item
android:id="@+id/genderFemale"
android:title="Female"
/>
</group>
</menu>
The function to execute the popup is as follows:
public void showGenderPopup(View v)
{
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.gender_popup, popup.getMenu());
popup.show();
}
Here the popupmenu
is being created just below the textview
when I am clicking it. I want it to be generated at the centre of the screen.
How to go about it?
As from docs says :
A PopupMenu displays a Menu in a modal popup window anchored to a View. The popup will appear below the anchor view if there is room, or above it if there is not. If the IME is visible the popup will not overlap it until it is touched. Touching outside of the popup will dismiss it.
As I may guess, that "View v"
public void showGenderPopup(View v)
is the TextView you are clicking, which is bound to the method when it is clicked, meaning the PopupMenu will show right below the TextView.
Wouldn't you achieve your goal with a Dialog? For a custom AlertDialog you just need to use method
setView(View v)
of the AlertDialog.Builder , before creating the Dialog itself.
For your custom View you either follow two ways:
XML: Create your XML layout file and then using an inflater to apply the XML Layout over a View customView object. (layout file is called customDialog.xml as an example)
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customView = inflater.inflate(R.layout.customDialog, null);
RadioButton radioButton = (RadioButton) customView.findViewById(R.id.customDialogRadioButton);
radioButton.setOnClickListener(new OnClickListener() { .. });
DYNAMICALLY :
I'll use LinearLayout as example.
LinearLayout customView = new LinearLayout(context);
RadioButton radioBtn = new RadioButton(context);
radioBtn.setOnClickListener(new OnClickListener() { .. });
customView.addView(radioBtn);
To create the dialog you then use this code
AlertDialog.Builder b = new AlertDialog.Builder(context);
b.setMessage("Example");
// set dialog's parameters from the builder
b.setView(customView);
Dialog d = b.create();
d.show();