Reputation: 3
I have added a button to the Action bar but now it is aligned to the far right like this
I want to align that button to the center like this.
How can I acheive this? Is there a way to do it without creating a custom Action bar?
This is the current layout of the Action bar. The button in question is the first <item>
.
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/post_your_notice"
android:background="@drawable/post_your_notice_button"
android:orderInCategory="10"
android:title="Post your notice"
app:showAsAction="always"
app:actionLayout="@layout/post_your_notice_button"/>
<item
android:id="@+id/action_logout"
android:orderInCategory="100"
android:title="Log out"
app:showAsAction="never" />
I have disabled the default title on the Action bar by calling
getSupportActionBar().setDisplayShowTitleEnabled(false);
on my Activity onCreate()
.
Upvotes: 0
Views: 977
Reputation:
Replace actionbar by android.support.v7.widget.Toolbar
where you can put Button
with android:layout_gravity="center"
.
Add support library dependency compile 'com.android.support:support-v13:25.3.1'
Define toolbar with button in your layout:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
...
>
<Button
android:id="@+id/toolbar_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
...
/>
</android.support.v7.widget.Toolbar>
Set toolbar in activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button button = (Button) findViewBydI(R.id.toolbar_button);
...
}
Upvotes: 2