当我点击操作栏中的操作按钮时,我会显示一个
PopupMenu.
我想在我的PopupMenu中的MenuItem,使用这样的自定义布局:
我想在我的PopupMenu中的MenuItem,使用这样的自定义布局:
布局/ menu_item_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/menuItemLayout" android:orientation="horizontal" > <ImageView android:id="@+id/imageViewMenuItem" android:layout_width="20dip" android:layout_height="20dip" android:src="@drawable/abc_list_focused_holo" /> <TextView android:id="@+id/textViewMenuItem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextViewMenuItem" /> </LinearLayout>
这是PopUpMenu的xml:
菜单/ pop_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context="apparound.actiobarpopupstylefacebook.Main" > <item android:id="@+id/popupItem" android:showAsAction="ifRoom"/> </menu>
在我的活动代码如下:
public void showPopup(int idR){ View menuItemView = findViewById(idR); PopupMenu popup = new PopupMenu(this,menuItemView); MenuInflater inflate = popup.getMenuInflater(); inflate.inflate(R.menu.pop_menu,popup.getMenu()); MenuItem menuItem= popup.getMenu().findItem(R.id.popupItem); menuItem.setActionView(R.layout.menu_item_layout); popup.show(); }
解决方法
对于自定义布局,您不能使用菜单,一个备用选项是
PopupWindow
PopupWindow popupwindow_obj = popupDisplay(); popupwindow_obj.showAsDropDown(clickbtn,-40,18); // where u want show on view click event popupwindow.showAsDropDown(view,x,y); public PopupWindow popupDisplay() { final PopupWindow popupWindow = new PopupWindow(this); // inflate your layout or dynamically add view LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.mylayout,null); Button item = (Button) view.findViewById(R.id.button1); popupWindow.setFocusable(true); popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); popupWindow.setContentView(view); return popupWindow; }
在名为my layout.xml的res / layout文件夹中创建此XML文件
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Window test" /> </LinearLayout>