簡體   English   中英

如何在 Android 中居中對齊 ActionBar 標題?

[英]How to center align the ActionBar title in Android?

我正在嘗試使用以下代碼將ActionBar的文本居中,但它會向左對齊。

你如何讓它出現在中心?

ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("Canteen Home");
actionBar.setHomeButtonEnabled(true);
actionBar.setIcon(R.drawable.back);

要在 ABS 中有一個居中的標題(如果你想在默認的ActionBar有這個,只需刪除方法名稱中的“支持”),你可以這樣做:

在您的活動中,在您的onCreate()方法中:

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" )。

或與:

getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.yourimage));

我在其他答案上沒有取得太大成功......下面正是使用支持庫 v7 中的 ActionBar 在 Android 4.4.3 上對我有用的內容。 我已將其設置為顯示導航抽屜圖標(“漢堡菜單按鈕”)

XML

    <?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:orientation="horizontal" >

    <TextView
        android:id="@+id/actionbar_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:maxLines="1"
        android:clickable="false"
        android:focusable="false"
        android:longClickable="false"
        android:textStyle="bold"
        android:textSize="18sp"
        android:textColor="#FFFFFF" />

</LinearLayout>

爪哇

//Customize the ActionBar
final ActionBar abar = getSupportActionBar();
abar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_background));//line under the action bar
View viewActionBar = getLayoutInflater().inflate(R.layout.actionbar_titletext_layout, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
        ActionBar.LayoutParams.WRAP_CONTENT, 
        ActionBar.LayoutParams.MATCH_PARENT, 
        Gravity.CENTER);
TextView textviewTitle = (TextView) viewActionBar.findViewById(R.id.actionbar_textview);
textviewTitle.setText("Test");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
abar.setDisplayHomeAsUpEnabled(true);
abar.setIcon(R.color.transparent);
abar.setHomeButtonEnabled(true);

正如 Sergii 所說,使用標題文本定義您自己的自定義視圖,然后將 LayoutParams 傳遞給 setCustomView()。

ActionBar actionBar = getSupportActionBar()
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
actionBar.setCustomView(getLayoutInflater().inflate(R.layout.action_bar_home, null),
        new ActionBar.LayoutParams(
                ActionBar.LayoutParams.WRAP_CONTENT,
                ActionBar.LayoutParams.MATCH_PARENT,
                Gravity.CENTER
        )
);

編輯:至少對於寬度,您應該使用 WRAP_CONTENT 或您的導航抽屜、應用程序圖標等。不會顯示(自定義視圖顯示在操作欄上的其他視圖之上)。 尤其是在未顯示操作按鈕時會發生這種情況。

編輯:等效於 xml 布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal"
    android:orientation="vertical">

這不需要指定 LayoutParams。

actionBar.setCustomView(getLayoutInflater().inflate(R.layout.action_bar_home, null);

只是對艾哈邁德回答的快速補充。 使用帶有 TextView 的自定義視圖時,您不能再使用 getSupportActionBar().setTitle。 因此,在您分配自定義視圖,在您的 onCreate() 方法中使用此自定義 ActionBar(使用此 xml)設置多個活動時設置標題:

TextView textViewTitle = (TextView) findViewById(R.id.mytext);
textViewTitle.setText(R.string.title_for_this_activity);

行。 經過大量研究,結合上面接受的答案,我提出了一個解決方案,如果您的操作欄中有其他內容(后退/主頁按鈕,菜單按鈕),該解決方案也有效。 所以基本上我已經將覆蓋方法放在一個基本活動中(所有其他活動都擴展了它),並將代碼放在那里。 此代碼設置每個活動的標題,因為它在 AndroidManifest.xml 中提供,並且還執行其他一些自定義內容(例如在操作欄按鈕上設置自定義色調,以及在標題上設置自定義字體)。 您只需要在 action_bar.xml 中忽略重力,並使用填充來代替。 actionBar != null檢查被使用,因為不是我所有的活動都有一個。

在 4.4.2 和 5.0.1 上測試

public class BaseActivity extends AppCompatActivity {
private ActionBar actionBar;
private TextView actionBarTitle;
private Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
    super.onCreate(savedInstanceState);     
    ...
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setElevation(0);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setCustomView(R.layout.action_bar);

        LinearLayout layout = (LinearLayout) actionBar.getCustomView();
        actionBarTitle = (TextView) layout.getChildAt(0);
        actionBarTitle.setText(this.getTitle());
        actionBarTitle.setTypeface(Utility.getSecondaryFont(this));
        toolbar = (Toolbar) layout.getParent();
        toolbar.setContentInsetsAbsolute(0, 0);

        if (this.getClass() == BackButtonActivity.class || this.getClass() == AnotherBackButtonActivity.class) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(true);
            Drawable wrapDrawable = DrawableCompat.wrap(getResources().getDrawable(R.drawable.ic_back));
            DrawableCompat.setTint(wrapDrawable, getResources().getColor(android.R.color.white));
            actionBar.setHomeAsUpIndicator(wrapDrawable);
            actionBar.setIcon(null);
        }
        else {
            actionBar.setHomeButtonEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(false);
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setHomeAsUpIndicator(null);
            actionBar.setIcon(null);
        }
    }

    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if(menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception ex) {
        // Ignore
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (actionBar != null) {
        int padding = (getDisplayWidth() - actionBarTitle.getWidth())/2;

        MenuInflater inflater = getMenuInflater();
        if (this.getClass() == MenuActivity.class) {
            inflater.inflate(R.menu.activity_close_menu, menu);
        }
        else {
            inflater.inflate(R.menu.activity_open_menu, menu);
        }

        MenuItem item = menu.findItem(R.id.main_menu);
        Drawable icon = item.getIcon();
        icon.mutate().mutate().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_IN);
        item.setIcon(icon);

        ImageButton imageButton;
        for (int i =0; i < toolbar.getChildCount(); i++) {
            if (toolbar.getChildAt(i).getClass() == ImageButton.class) {
                imageButton = (ImageButton) toolbar.getChildAt(i);
                padding -= imageButton.getWidth();
                break;
            }
        }

        actionBarTitle.setPadding(padding, 0, 0, 0);
    }

    return super.onCreateOptionsMenu(menu);
} ...

而我的 action_bar.xml 是這樣的(如果有人感興趣的話):

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/actionbar_text_color"
        android:textAllCaps="true"
        android:textSize="9pt"
        />

</LinearLayout>

編輯:如果您需要在加載活動后將標題更改為其他內容(已調用 onCreateOptionsMenu),請將另一個 TextView 放入 action_bar.xml 並使用以下代碼“填充”此新 TextView,設置文本並顯示它:

protected void setSubTitle(CharSequence title) {

    if (!initActionBarTitle()) return;

    if (actionBarSubTitle != null) {
        if (title != null || title.length() > 0) {
            actionBarSubTitle.setText(title);
            setActionBarSubTitlePadding();
        }
    }
}

private void setActionBarSubTitlePadding() {
    if (actionBarSubTitlePaddingSet) return;
    ViewTreeObserver vto = layout.getViewTreeObserver();
    if(vto.isAlive()){
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int padding = (getDisplayWidth() - actionBarSubTitle.getWidth())/2;

                ImageButton imageButton;
                for (int i = 0; i < toolbar.getChildCount(); i++) {
                    if (toolbar.getChildAt(i).getClass() == ImageButton.class) {
                        imageButton = (ImageButton) toolbar.getChildAt(i);
                        padding -= imageButton.getWidth();
                        break;
                    }
                }

                actionBarSubTitle.setPadding(padding, 0, 0, 0);
                actionBarSubTitlePaddingSet = true;
                ViewTreeObserver obs = layout.getViewTreeObserver();
                obs.removeOnGlobalLayoutListener(this);
            }
        });
    }
}

protected void hideActionBarTitle() {

    if (!initActionBarTitle()) return;

    actionBarTitle.setVisibility(View.GONE);
    if (actionBarSubTitle != null) {
        actionBarSubTitle.setVisibility(View.VISIBLE);
    }
}

protected void showActionBarTitle() {

    if (!initActionBarTitle()) return;

    actionBarTitle.setVisibility(View.VISIBLE);
    if (actionBarSubTitle != null) {
        actionBarSubTitle.setVisibility(View.GONE);
    }
}

編輯(25.08.2016) :如果您的活動有“后退按鈕”,這不適用於 appcompat 24.2.0 修訂版(2016 年 8 月)。 我提交了一個錯誤報告(問題 220899 ),但我不知道它是否有任何用處(懷疑它會很快被修復)。 同時解決方案是檢查孩子的類是否等於 AppCompatImageButton.class 並執行相同的操作,僅將寬度增加 30%(例如 appCompatImageButton.getWidth()*1.3 在從原始填充中減去此值之前):

padding -= appCompatImageButton.getWidth()*1.3;

與此同時,我在那里加入了一些填充/邊距檢查:

    Class<?> c;
    ImageButton imageButton;
    AppCompatImageButton appCompatImageButton;
    for (int i = 0; i < toolbar.getChildCount(); i++) {
        c = toolbar.getChildAt(i).getClass();
        if (c == AppCompatImageButton.class) {
            appCompatImageButton = (AppCompatImageButton) toolbar.getChildAt(i);
            padding -= appCompatImageButton.getWidth()*1.3;
            padding -= appCompatImageButton.getPaddingLeft();
            padding -= appCompatImageButton.getPaddingRight();
            if (appCompatImageButton.getLayoutParams().getClass() == LinearLayout.LayoutParams.class) {
                padding -= ((LinearLayout.LayoutParams) appCompatImageButton.getLayoutParams()).getMarginEnd();
                padding -= ((LinearLayout.LayoutParams) appCompatImageButton.getLayoutParams()).getMarginStart();
            }
            break;
        }
        else if (c == ImageButton.class) {
            imageButton = (ImageButton) toolbar.getChildAt(i);
            padding -= imageButton.getWidth();
            padding -= imageButton.getPaddingLeft();
            padding -= imageButton.getPaddingRight();
            if (imageButton.getLayoutParams().getClass() == LinearLayout.LayoutParams.class) {
                padding -= ((LinearLayout.LayoutParams) imageButton.getLayoutParams()).getMarginEnd();
                padding -= ((LinearLayout.LayoutParams) imageButton.getLayoutParams()).getMarginStart();
            }
            break;
        }
    }

沒有 customview 它能夠將操作欄標題居中。 它也非常適合導航抽屜

    int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
    TextView abTitle = (TextView) findViewById(titleId);
    abTitle.setTextColor(getResources().getColor(R.color.white));

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    abTitle.setGravity(Gravity.CENTER);
    abTitle.setWidth(metrics.widthPixels);
    getActionBar().setTitle("I am center now");

快樂編碼。 謝謝。

代碼在這里為我工作。

    // Activity 
 public void setTitle(String title){
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(this);
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(textView);
} 

// Fragment
public void setTitle(String title){
    ((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(getActivity());
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(textView);
}

經過大量研究:這實際上有效:

 getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
 getActionBar().setCustomView(R.layout.custom_actionbar);
  ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        p.gravity = Gravity.CENTER;

您必須根據您的要求定義 custom_actionbar.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="50dp"
    android:background="#2e2e2e"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/top_banner"
        android:layout_gravity="center"
        />
</LinearLayout>

它工作得很好。

activity = (AppCompatActivity) getActivity();

activity.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.custom_actionbar, null);

ActionBar.LayoutParams p = new ActionBar.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT,
        Gravity.CENTER);

((TextView) v.findViewById(R.id.title)).setText(FRAGMENT_TITLE);

activity.getSupportActionBar().setCustomView(v, p);
activity.getSupportActionBar().setDisplayShowTitleEnabled(true);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

custom_actionbar 的布局如下:

<?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="match_parent">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:text="Example"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/colorBlack" />

</RelativeLayout>

不需要更改 XML 布局的 Kotlin-only 解決方案:

//Function to call in onResume() of your activity
private fun centerToolbarText() {
    val mTitleTextView = AppCompatTextView(this)
    mTitleTextView.text = title
    mTitleTextView.setSingleLine()//Remove it if you want to allow multiple lines in the toolbar
    mTitleTextView.textSize = 25f
    val layoutParams = android.support.v7.app.ActionBar.LayoutParams(
        ActionBar.LayoutParams.WRAP_CONTENT,
        ActionBar.LayoutParams.WRAP_CONTENT
    )
    layoutParams.gravity = Gravity.CENTER
    supportActionBar?.setCustomView(mTitleTextView,layoutParams)
    supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
}

您需要設置ActionBar.LayoutParams.WRAP_CONTENTActionBar.DISPLAY_HOME_AS_UP

View customView = LayoutInflater.from(this).inflate(R.layout.actionbar_title, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
                ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP );

最好和最簡單的方法,特別適合那些只想要重心文本視圖而沒有任何 xml 布局的人。

AppCompatTextView mTitleTextView = new AppCompatTextView(getApplicationContext());
        mTitleTextView.setSingleLine();
        ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        actionBar.setCustomView(mTitleTextView, layoutParams);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_HOME_AS_UP);
        mTitleTextView.setText(text);
        mTitleTextView.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Medium);

這是一個完整的 Kotlin + androidx 解決方案,基於 @Stanislas Heili 的答案。 我希望它對其他人有用。 當您有一個活動承載多個片段時,只有一個片段同時處於活動狀態。

在您的活動中:

private lateinit var customTitle: AppCompatTextView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // stuff here
    customTitle = createCustomTitleTextView()
    // other stuff here
}

private fun createCustomTitleTextView(): AppCompatTextView {
    val mTitleTextView = AppCompatTextView(this)
    TextViewCompat.setTextAppearance(mTitleTextView, R.style.your_style_or_null);

    val layoutParams = ActionBar.LayoutParams(
        ActionBar.LayoutParams.WRAP_CONTENT,
        ActionBar.LayoutParams.WRAP_CONTENT
    )
    layoutParams.gravity = Gravity.CENTER
    supportActionBar?.setCustomView(mTitleTextView, layoutParams)
    supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM

    return mTitleTextView
}

override fun setTitle(title: CharSequence?) {
    customTitle.text = title
}

override fun setTitle(titleId: Int) {
    customTitle.text = getString(titleId)
}

在你的片段中:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    activity?.title = "some title for fragment"
}

我見過的其他教程覆蓋了隱藏 MenuItems 的整個操作欄布局。 我只需執行以下步驟即可工作:

創建一個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="match_parent" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="@string/app_name"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/white" />

</RelativeLayout>

在課堂上這樣做:

LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.action_bar_title, null);

ActionBar.LayoutParams params = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);

TextView titleTV = (TextView) v.findViewById(R.id.title);
titleTV.setText("Test");

對於 Kotlin 用戶:

在您的活動中使用以下代碼:

// Set custom action bar
supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
supportActionBar?.setCustomView(R.layout.action_bar)

// Set title for action bar
val title = findViewById<TextView>(R.id.titleTextView)
title.setText(resources.getText(R.string.app_name))

和 XML/資源布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/titleTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textColor="@color/black"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

我的解決方案是將工具欄的文本部分分開,定義樣式並說,居中或任何對齊方式。 它可以在 XML 本身中完成。 當您有始終可見的操作時,可以在計算后指定一些填充。 我已將兩個屬性從工具欄移動到其子 TextView。 這個 textView 可以提供 id 以從片段訪問。

    <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" >
            <!--android:theme="@style/defaultTitleTheme"
            app:titleTextColor="@color/white"-->
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:paddingStart="@dimen/icon_size"
                android:text="@string/title_home"
                style="@style/defaultTitleTheme"
                tools:ignore="RtlSymmetry" />
        </androidx.appcompat.widget.Toolbar>
    </com.google.android.material.appbar.AppBarLayout>

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

以下是將動作居中對齊的快速提示:

android:label=" YourTitle"

假設您啟用了 Actionbar,您可以將其添加到您的活動中,並留出一些空間(可以調整)以將標題放置在中心。

然而,這只是簡單且不可靠的方法。 你可能不應該這樣做。 所以,最好的辦法是創建一個自定義的 ActionBar。 所以,您想要做的是刪除默認的 Actionbar 並使用它來將其替換為 ActionBar。

<androidx.constraintlayout.widget.ConstraintLayout
        android:elevation="30dp"
        android:id="@+id/customAction"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="@color/colorOnMain"
        android:orientation="horizontal">
        

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:textAllCaps="true"
            android:textColor="#FFF"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

我使用約束布局將 textView 居中,並使用 10dp 高程和 56dp 高度,使其看起來與默認 ActionBar 相同。

此代碼不會隱藏后退按鈕,同時將標題居中對齊。

在 oncreate 中調用此方法

centerActionBarTitle();



getSupportActionBar().setDisplayHomeAsUpEnabled(true);
myActionBar.setIcon(new ColorDrawable(Color.TRANSPARENT));

private void centerActionBarTitle() {
    int titleId = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        titleId = getResources().getIdentifier("action_bar_title", "id", "android");
    } else {
        // This is the id is from your app's generated R class when 
        // ActionBarActivity is used for SupportActionBar
        titleId = R.id.action_bar_title;
    }

    // Final check for non-zero invalid id
    if (titleId > 0) {
        TextView titleTextView = (TextView) findViewById(titleId);
        DisplayMetrics metrics = getResources().getDisplayMetrics();

        // Fetch layout parameters of titleTextView 
        // (LinearLayout.LayoutParams : Info from HierarchyViewer)
        LinearLayout.LayoutParams txvPars = (LayoutParams) titleTextView.getLayoutParams();
        txvPars.gravity = Gravity.CENTER_HORIZONTAL;
        txvPars.width = metrics.widthPixels;
        titleTextView.setLayoutParams(txvPars);
        titleTextView.setGravity(Gravity.CENTER);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM