java Android - 在点击 ActionBar 按钮时创建一个 PopupMenu

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15834332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:59:45  来源:igfitidea点击:

Android - Creating a PopupMenu on clicking an ActionBar button

javaandroidandroid-actionbarruntimeexceptionpopupmenu

提问by ARampal

I am trying to make a PopupMenu appear after I click a button in an action bar.

我试图在单击操作栏中的按钮后显示 PopupMenu。

I have got the buttons in the file - action.xmlin the 'menu' folder.

我有文件中的按钮 -action.xml在“ menu”文件夹中。

This contains the buttons for the ActionBar.

这包含 ActionBar 的按钮。

<item
    android:id="@+id/overflow"
    android:icon="@drawable/ic_action_overflow"
    android:orderInCategory="2"
    android:menuCategory="container"
    android:title="Overflow Button"       
    android:showAsAction="ifRoom|withText"
    android:onClick="**showPopup**"
    />

<item
    android:id="@+id/add"
    android:icon="@drawable/add"
    android:title="Add Button"
    android:orderInCategory="100"
    android:showAsAction="ifRoom|withText"
    android:onClick="**showPopup**"
    />

Once a button is clicked I wish to have a PopupMenuto be shown. The showPopupmethod is located in the FragmentActivityclass:

单击按钮后,我希望PopupMenu显示一个。该showPopup方法位于FragmentActivity类中:

 public void showPopup(MenuItem v) {        
        PopupMenu popup = new PopupMenu(this, this.getCurrentFocus());      
        popup.inflate(R.layout.pop);        
        popup.show();       
        }

The pop.xmlfile is stored in the layout folder (and contains the view of the pop up menu)

pop.xml文件存储在布局文件夹中(并包含弹出菜单的视图)

Unfortunately this is giving me a RuntimeException java.lang.reflect.InvocationTargetException.

不幸的是,这给了我一个RuntimeException java.lang.reflect.InvocationTargetException.

Any ideas?

有任何想法吗?

Help would be greatly appreciated.

帮助将不胜感激。

回答by Mike Shadoff

First of all, this is quite easy.

首先,这很容易。

You have to add this attribute to your actionBar item.

您必须将此属性添加到您的 actionBar 项目。

android:onClick="openPopup"

openPopupis your popup method.

openPopup是你的弹出方法。

Then, in your MainActivitywhich is by the way supposed to extend ActionBarActivity
you have to add your method that will be called onClick.

然后,在MainActivity应该扩展的方式中,ActionBarActivity
您必须添加将被调用的方法onClick

public void openPopup(MenuItem item){ 
      Point p;
      p.x = 0;
      p.y = 0;
      showPopup(MainActivity.this, p);
      Toast.makeText(this, "Popup Should Open", Toast.LENGTH_LONG).show();
  } 

And of course the showPopupmethod.

当然还有showPopup方法。

private void showPopup(final Activity context, Point p) {

   // Inflate the popup_layout.xml
   LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
   LayoutInflater layoutInflater = (LayoutInflater) context
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);

   // Creating the PopupWindow
   final PopupWindow popup = new PopupWindow(context);
   popup.setContentView(layout);
   popup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
   popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
   popup.setFocusable(true);

   popupWidth = popup.getWidth();

   // Clear the default translucent background
   popup.setBackgroundDrawable(new BitmapDrawable(this.getResources()));

   // Displaying the popup at the specified location.
   popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x, p.y);

   // Getting a reference to Close button, and close the popup when clicked.
   Button close = (Button) layout.findViewById(R.id.close);
   close.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
       popup.dismiss();
     }
   });
}

That's it.

而已。

回答by Tarun

I would like to share the way I do it. Let us say we have a Button(or any clicakbale view be it anywhere) with id "btn" and we want to attach a popupMenu on its click. Put the menu you want to display in menu folder in following xml say "menu1.xml".

我想分享我的做法。假设我们有一个 ID 为“btn”的 Button(或任何地方的任何 clicakbale 视图),我们想在点击时附加一个 popupMenu。将要显示的菜单放在下面的 xml 中的菜单文件夹中,说“menu1.xml”。

OnClick of button is defined as follows :

按钮的 OnClick 定义如下:

Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupMenu(v);
            }
        });

showPopupMenu() is defined as below :

showPopupMenu() 定义如下:

private void showPopupMenu(View view) {
    // inflate menu and attach it to a view onClick of which you want to display menu
    PopupMenu popup = new PopupMenu(mContext, view);
    MenuInflater inflater = popup.getMenuInflater();
    //inflate menu items to popup menu
    inflater.inflate(R.menu.menu1, popup.getMenu());
    //assign a cutom onClick Listener to it.
    popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
    //Show Popup.
    popup.show();
}

Complete post can be found here : http://revisitingandroid.blogspot.in/2017/01/how-to-display-popup-menu-on-any-view.html

完整的帖子可以在这里找到:http: //revisitingandroid.blogspot.in/2017/01/how-to-display-popup-menu-on-any-view.html

回答by Waqas Memon

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="20sp"
        android:textColor="#000000"
        android:layout_margin="20dip"
        android:text="Popup Menu Example" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Touch here to see the menu."
        android:layout_margin="20dip"
        android:layout_gravity="center"
        android:textColor="#0000ff"
        android:id="@+id/anchor"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dip"
        android:layout_gravity="center"
        android:textSize="40sp"
        android:textColor="#808080"
        android:id="@+id/selection"/>
</LinearLayout>

package com.authorwjf.popmenu;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import android.app.Activity;
public class Main extends Activity implements OnClickListener, OnMenuItemClickListener
{

       private PopupMenu popupMenu;
       private final static int ONE = 1;
       private final static int TWO = 2;
       private final static int THREE = 3;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
             popupMenu = new PopupMenu(this, findViewById(R.id.anchor));
             popupMenu.getMenu().add(Menu.NONE, ONE, Menu.NONE, "Item 1");
             popupMenu.getMenu().add(Menu.NONE, TWO, Menu.NONE, "Item 2");
             popupMenu.getMenu().add(Menu.NONE, THREE, Menu.NONE, "Item 3");
             popupMenu.setOnMenuItemClickListener(this);
             findViewById(R.id.anchor).setOnClickListener(this);
       }
}


@Override
public void onClick(View v) {
       popupMenu.show();
}


@Override
public boolean onMenuItemClick(MenuItem item) {
       TextView tv = (TextView) findViewById(R.id.selection);
       switch (item.getItemId()) {
       case ONE:
              tv.setText("ONE");
              break;
       case TWO:
              tv.setText("TWO");
              break;
       case THREE:
              tv.setText("THREE");
              break;
       }
       return false;
}