Center align right aligned button on Action Bar

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 08:48:17

问题


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().


回答1:


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);
    ...
}


来源:https://stackoverflow.com/questions/45265072/center-align-right-aligned-button-on-action-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!