如何在 Android 中居中对齐 ActionBar 标题? [英] How to center align the ActionBar title in Android?
问题描述
我正在尝试使用以下代码将 ActionBar
中的文本居中,但它会向左对齐.
I am trying to use the following code to center the text in the ActionBar
, but it aligns itself to the left.
你如何让它出现在中心?
How do you make it appear in the center?
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("Canteen Home");
actionBar.setHomeButtonEnabled(true);
actionBar.setIcon(R.drawable.back);
推荐答案
要在 ABS 中有一个居中的标题(如果你想在默认的 ActionBar
中有这个,只需删除方法名称),你可以这样做:
To have a centered title in ABS (if you want to have this in the default ActionBar
, just remove the "support" in the method names), you could just do this:
在您的活动中,在您的 onCreate()
方法中:
In your Activity, in your onCreate()
method:
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
abs_layout
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<android.support.v7.widget.AppCompatTextView
android:id="@+id/tvTitle"
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#FFFFFF" />
</LinearLayout>
现在你应该有一个只有标题的 Actionbar
.如果要设置自定义背景,请在上面的 Layout 中进行设置(但不要忘记设置 android:layout_height="match_parent"
).
Now you should have an Actionbar
with just a title. If you want to set a custom background, set it in the Layout above (but then don't forget to set android:layout_height="match_parent"
).
或与:
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.yourimage));
这篇关于如何在 Android 中居中对齐 ActionBar 标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!