微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android MenuItem自定义布局

当我点击操作栏中的操作按钮时,我会显示一个 PopupMenu.
我想在我的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();
}

但是当弹出菜单出现时,项目为空.
我使用setActionview()方法错误的?
谢谢.

解决方法

对于自定义布局,您不能使用菜单,一个备用选项是 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>

原文地址:https://www.jb51.cc/android/313681.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐