Android 弹出菜单位置

Android popupmenu position

我正在尝试制作一个 android 应用程序,点击按钮会引发 popupmenupopupmenu 正在生成,但位置不正确。代码如下:

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>

弹窗执行函数如下:

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();
}

这里 popupmenu 是在我单击它时在 textview 下方创建的。我想让它在屏幕中央生成。

怎么办?

  PopupMenu popup = new PopupMenu(this, v,Gravity.CENTER);  

使用上面的代码。 Gravity 有很多选项,比如 center/left/right 查看文档 ocne

正如文档所说:

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.

正如我猜测的那样,"View v"

public void showGenderPopup(View v)

是你点击的TextView,点击时绑定到方法,即PopupMenu会显示在TextView的正下方。

你不会用对话来实现你的目标吗?对于自定义 AlertDialog,您只需要使用 method

setView(View v)

的 AlertDialog.Builder ,在创建对话框本身之前。

对于您的自定义视图,您可以采用两种方式:

XML: 创建 XML 布局文件,然后使用 inflater 将 XML 布局应用于 View customView 对象。 (布局文件名为customDialog.xml为例)

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() { .. });

动态:

我将使用 LinearLayout 作为示例。

LinearLayout customView = new LinearLayout(context);

RadioButton radioBtn = new RadioButton(context); 
radioBtn.setOnClickListener(new OnClickListener() { .. });

customView.addView(radioBtn);

然后使用此代码创建对话框

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();