工具栏菜单项之间的视图

3

是否可以在工具栏菜单项中添加视图?

我希望像黄色部分一样在两个工具栏菜单项之间显示视图。


这可能是可行的,但您必须忽略此视图的单击事件。简而言之,您有一个分隔视图,但实际上它是一个“菜单项”,但在单击按钮时,您必须忽略其单击行为。 - Murtaza Khursheed Hussain
选取三个菜单项,并设置属性app:showAsAction="always",其中第二个菜单项的drawable来源将是分隔线图片。 - Kapil Rajput
2个回答

1
只需在xml文件中创建分隔线视图以显示分隔线。

dividerLine.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<View
android:layout_width="1dp"
android:layout_height="?android:attr/actionBarSize" 
android:background="@android:color/darker_gray"/> 
 </LinearLayout>

将菜单xml中的一个项目设置为actionLayout,以显示分隔线。

activity_menu.xml

 <menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/your_icon1"
      android:icon="@drawable/image1"
      android:title="@string/text1"
      app:showAsAction="always"
      />

<item android:id="@+id/icon2TricktoShowDividerLine"
     android:actionLayout="@layout/dividerLine" 
     app:showAsAction="always"
     android:title="@string/text2" />

<item android:id="@+id/your_icon3"
      android:icon="@drawable/icon"
      android:title="@string/text3"
      app:showAsAction="always" />
 </menu>

android:actionLayout="@layout/dividerLine" 显示菜单项之间的分割线。希望这能对您有所帮助。
更新
我从上面的代码中得到了这种类型的视图:

enter image description here


你试过了吗?因为它在工具栏中不可见。 - Salman khan
@Salmankhan 是的,我已经尝试过了,对我来说运行良好。尝试在“dividerLine.xml”中更改视图的背景颜色以使其可见。 - Kapil Rajput
我已经尝试使用不同的颜色,但完全看不到。请向我展示具有分隔视图工具栏的演示或图像。 - Salman khan
@Salmankhan,请查看我在答案中更新的截图。 - Kapil Rajput
需要使用 app:actionLayout 而不是 android:actionLayout。无论如何,感谢你的帮助。 - Salman khan

0
你需要使用 actionLayout 创建 menuItem 的自定义布局,然后在 onCreateOptionsMenu 中获取 menuItem 视图并将其图标更改为垂直可绘制的图标。

layout_actionitem.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView
        android:id="@+id/actionItemImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="1dp"/>

</LinearLayout>

您的菜单 XML

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/item_save"
        android:icon="@drawable/exit"
        android:showAsAction="always"
        android:actionLayout="@layout/layout_actionitem"
        android:title=""/>
</menu>

onCreateOptionsMenu

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        LinearLayout actionItemLayout = (LinearLayout) menu.findItem(R.id.item_save).getActionView();
        ImageView iv = (ImageView)actionItemLayout.findViewById(R.id.actionItemImage);
        iv.setBackgroundDrawable(getResources().getDrawable(R.drawable.icon_save));
}

希望这能有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接