user3179245
user3179245

Reputation: 53

Actionbar using customview and menuitems

ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
actionBar.setCustomView(R.layout.myLayout);

...

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    getMenuInflater().inflate(R.menu.myMenu, menu);

    menuBar = menu;

    return true;
}

myLayout.xml

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

 <ImageView
    android:layout_width="40dp" 
    android:layout_height="40dp"
    android:layout_centerInParent="true"
    android:src="@drawable/myImage" />
</RelativeLayout>

myMenu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/menuItem1"
    android:icon="@drawable/icon1"
    android:showAsAction="always"
    android:visible="false"
    android:title="@string/menu1">
</item>
<item
    android:id="@+id/menuItem2"
    android:icon="@drawable/icon2"
    android:showAsAction="always"
    android:title="@string/menu2">
</item>

</menu>

I have a custom view which I use to place an image in the center of the ActionBar. However, when I put the MenuItems on the ActionBar, the image gets pushed to the left. I don't know how to center the image or fill the RelativeLayout to take the entire ActionBar width. I tried many different things but so far I had no luck. Any help would be appreciated.

Upvotes: 0

Views: 514

Answers (1)

Submersed
Submersed

Reputation: 8870

When you add your custom view to the ActionBar, you can set custom ActionBar.LayoutParams for your View.

To do what you're trying to do, you could change your code to something like:

mLayout.xml

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

 <ImageView
    android:layout_width="40dp" 
    android:layout_height="40dp"
    android:src="@drawable/myImage" />

</LinearLayout>

Called somewhere in onCreate(Bundle b):

public void setUpActionBar(){
     View view = getLayoutInflater().inflate(R.layout.mLayout);

     ActionBar.LayoutParams lp = new ActionBar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);

     final ActionBar bar = getActionBar();
     bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
     bar.setCustomView(view, lp);

}

Upvotes: 1

Related Questions