1

I've created a custom ActionBar with a simple TextView, the text is supposed to be aligned to the center. Then I added a MenuItem with onCreateOptionsMenu method. The result was that the each of the components were at each side of the ActionBar, the menu-item was placed at the left corner and the text-view was placed at the right corner. How can I make the text-view remain centered despite adding menu-items to the action-bar?

Here is my custom action_bar_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/app_name"
        android:textColor="#ffffff"
        android:id="@+id/action_bar_text"
        android:textSize="18sp"/>

</LinearLayout>

Here is my menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.rashish.myapplication.MainActivity">

    <item
        android:id="@+id/back_action"
        android:orderInCategory="100"
        android:title="@string/back"
        app:showAsAction="always"/>

</menu>

Here is my onCreateOptionsMenu method:

public boolean onCreateOptionsMenu(Menu menu) {
        this.mMenu = menu;
        getMenuInflater().inflate(R.menu.menu_main, mMenu);
        MenuItem item = menu.findItem(R.id.back_action);
        item.setVisible(true);

        return true;
    }

and this is how I use my custom action bar in onCreate method

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            getSupportActionBar().setCustomView(R.layout.action_bar_layout);

//MORE CODE
Keselme
  • 3,779
  • 7
  • 36
  • 68

0 Answers0