【问题标题】:How to add a RelativeLayout as menu item - Android如何将 RelativeLayout 添加为菜单项 - Android
【发布时间】:2023-03-02 23:15:01
【问题描述】:

我有一个带有 itemgroup 的菜单 XML。我打算在 XML 中添加一个 RelativeLayout 作为菜单项,使其看起来像:

<menu>
    <item1/>
    <item2
         <RelativeLayout>
               <TextView1/>
               <TextView2/>
         <RelativeLayout>
    />
</menu>

这可以在布局 XML 中完成,还是以编程方式完成?如果没有,解决方法会有所帮助。谢谢。

【问题讨论】:

    标签: android android-layout android-relativelayout android-xml android-menu


    【解决方案1】:

    用你想要的视图创建一个布局文件,然后像这样使用它 -

    <item
        android:id="@+id/menu_refresh"
        android:title="@string/refresh"
        yourapp:showAsAction="never"
        android:actionLayout="@layout/my_custom_layout"/>
    

    编辑你的文本视图 -

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    
        //Get a reference to your item by id
        MenuItem item = menu.findItem(R.id.menu_refresh);
    
        //Here, you get access to the view of your item, in this case, the layout of the item has a RelativeLayout as root view but you can change it to whatever you use
        RelativeLayout rootView = (RelativeLayout)item.getActionView();
    
        //Then you access to your control by finding it in the rootView
        TextView textview1 = (TextView) rootView.findViewById(R.id.text1);
    
        //And from here you can do whatever you want with your text view
    
        return true;
    }
    

    【讨论】:

    • 谢谢。我认为这应该有效。虽然,我怎样才能以编程方式获取TextView1 以动态设置文本?
    【解决方案2】:

    重点:

    要使用Relativelayout 或任何其他布局,您必须使用actionLayout 作为@Jack 的延迟代码答案。但请记住这一点。

    android:actionLayout="@layout/my_custom_layout" 不行,你必须使用app:actionLayout="@layout/my_custom_layout"

    因为如果您使用ActionbarSherlockAppCompatandroid: 命名空间将不适用于MenuItems。这是因为这些库使用模仿 Android API 的自定义属性,因为它们在框架的早期版本中不存在。

    【讨论】:

      【解决方案3】:

      不能直接放在menu.xml中,要使用android:actionLayout属性。

      它是这样工作的:

      menu.xml

      <menu>
          <item ... android:actionLayout="@layout/custom_layout"/>
      </menu>
      

      custom_layout.xml

      <RelativeLayout ...>
          <TextView .../>
          <TextView .../>
      <RelativeLayout>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-04
        • 2012-01-08
        • 2012-10-09
        • 2017-02-18
        • 2012-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多