Android自定义后退按钮带有文本

问题描述:

我想要在我的Android应用程序中创建一个动作栏,就像我在iOS应用程序中拥有的一样:

I want in my Android app an action bar like the one I have in my iOS app:

.

不幸的是,我不知道如何使后退按钮仅包含文本,以及如何将标题移到中间.这将适用于整个应用程序,而不仅仅是一种布局.

Unfortunately I don't know how to make the back button with text only and how to move the title in the center. This would be for the entire application, not only one layout.

请问有人可以帮我吗?

我找到了一个简单的解决方案.

I have found a simple solution.

您只需为自定义ActionBar custom_action_bar_layout.xml

You have just to create a layout for a custom ActionBar custom_action_bar_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="50dp"
   android:background="@color/colorPrimary">

    <TextView
        android:id="@+id/title_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textAllCaps="true"
        android:text="name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#fff"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/back_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#fff"
        android:text="Back"/>

</RelativeLayout>

,然后在您的ExampleActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_date);

    ActionBar mActionBar = getSupportActionBar();
    mActionBar.setDisplayShowHomeEnabled(false);
    mActionBar.setDisplayShowTitleEnabled(false);
    LayoutInflater mInflater = LayoutInflater.from(this);

    View mCustomView = mInflater.inflate(R.layout.custom_action_bar_layout, null);
    TextView title = (TextView) mCustomView.findViewById(R.id.title_text);
    title.setText("Title");
    TextView backButton = (TextView) mCustomView.findViewById(R.id.back_button);
    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);
}

这就是结果.