Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MenuItem actionView aligns right

As the title says, I'm setting using setActionView on a MenuItem, here's the layout:

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

    <ProgressBar
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_margin="4dp"
        android:layout_centerInParent="true"/>

</RelativeLayout>

The issue is that the ProgressBar appears aligned to the right. (It should be aligned to the center, same as the MenuItem icon. Icons are 32dp

How can I achieve this?

like image 789
Christopher Francisco Avatar asked Sep 16 '25 05:09

Christopher Francisco


1 Answers

I faced similar issue today and coudn't find any good QA on SO. Hence I did some research. Here are my findings on the matter:

Android Menu is implemented in this way:

If you have inflated an actionView to have:

  • icon (optional)
  • title (optional, or to say it can be made optional by setting it as "")
  • a custom view

and you don't set icon, set title as "" and set actionView to make the menuItem appear to contain only the custom view which you inflated using setActionView, then:

enter image description here

Android forces the custom view's width to be wrap_content and remaining area gets occupied by icon+title of the menuItem.

We can think of this implementation as:

enter image description here

enter image description here

Think of the entire view after margin as ParentLinearLayout which is divided into LinearLayout1 and LinearLayout2 (depicted in the image above as Layout 1 and Layout 2 respectively)

Now LinearLayout1 has width=0dp and weight=1 And LinearLayout2 has width=wrap_content

Hence no matter what we set, currently, we cannot right align the inflated custom view (action view) in menu.

To be technically accurate, you can right align if you really need this done by checking out the internal implementation code for the navigation menu by Android. But not really worth the effort. Any feature is a tradeoff of time required vs outcome.

like image 84
mumayank Avatar answered Sep 18 '25 17:09

mumayank