其他分享
首页 > 其他分享> > Android弹出菜单位置

Android弹出菜单位置

作者:互联网

我正在尝试制作一个Android应用程序,点击一个按钮引发一个弹出菜单.弹出菜单正在生成但不在正确的位置.代码如下:

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

当我点击它时,弹出菜单正在textview下方创建.我希望它在屏幕的中心生成.

怎么去呢?

解决方法:

从文档中可以看出:

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的正下方.

你不是用Dialog实现目标吗?对于自定义AlertDialog,您只需要使用方法

setView(View v)

在创建Dialog本身之前,AlertDialog.Builder.

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

XML:
创建XML布局文件,然后使用inflater通过View customView对象应用XML布局. (布局文件以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();

标签:popupmenu,android
来源: https://codeday.me/bug/20191007/1869251.html