我试图在单击操作栏中的按钮后显示弹出菜单。
我在“menu
”文件夹中的文件 - action.xml
中找到了按钮。
其中包含 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**"
/>
单击按钮后,我希望显示一个 PopupMenu
。 showPopup
方法位于 FragmentActivity
类中:
public void showPopup(MenuItem v) {
PopupMenu popup = new PopupMenu(this, this.getCurrentFocus());
popup.inflate(R.layout.pop);
popup.show();
}
pop.xml
文件存储在布局文件夹中(并包含弹出菜单的 View )
不幸的是,这给了我一个RuntimeException java.lang.reflect.InitationTargetException
。
有什么想法吗?
非常感谢您的帮助。
最佳答案
首先,这非常简单。
您必须将此属性添加到您的actionBar 项目中。
android:onClick="openPopup"
openPopup
是您的弹出方法。
然后,在您的 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();
}
当然还有 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();
}
});
}
就是这样。
关于java - Android - 单击 ActionBar 按钮时创建 PopupMenu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15834332/