Jak wyśrodkować tytuł ActionBar w systemie Android?

99

Próbuję użyć następującego kodu, aby wyśrodkować tekst w ActionBar, ale wyrównuje się do lewej.

Jak sprawiasz, że pojawia się w środku?

ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("Canteen Home");
actionBar.setHomeButtonEnabled(true);
actionBar.setIcon(R.drawable.back);
Sourabh Saldi
źródło
To jest BARDZO stare pytanie. Jednak jedynym rozwiązaniem, które widzę poniżej, jest utworzenie niestandardowego paska akcji. Oto rozwiązanie bez tworzenia niestandardowego paska akcji. stackoverflow.com/a/42465266/3866010 mam nadzieję, że to komuś pomoże
ᴛʜᴇᴘᴀᴛᴇʟ
1
Prawie 8 lat po tym, jak zadałem to pytanie, używając ponownie odpowiedzi: D
Sourabh Saldi

Odpowiedzi:

197

Aby mieć wyśrodkowany tytuł w ABS (jeśli chcesz mieć ten domyślny ActionBar, po prostu usuń "wsparcie" w nazwach metod), możesz po prostu zrobić to:

W swojej aktywności, w swojej onCreate()metodzie:

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>

Teraz powinieneś mieć Actionbartylko tytuł. Jeśli chcesz ustawić niestandardowe tło, ustaw je w powyższym układzie (ale nie zapomnij ustawić android:layout_height="match_parent").

lub z:

getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.yourimage));
Ahmad
źródło
6
jak dodać do tego niestandardowy obraz przycisku Wstecz?
Sourabh Saldi
13
Dla mnie wynik był taki, że pasek akcji był nieco przesunięty w prawo lub w lewo, w zależności od przycisków akcji, które pokazywałem. Aby to naprawić, po prostu ustawiłem layout_width na „WRAP_CONTENT”
alfongj
11
Rozwiązanie Pepillo nie zadziałało dla mnie, ponieważ treść nie była już w ogóle wyśrodkowana. Mogę rozwiązać ten problem, dodając android:layout_gravity="center"do LinearLayout.
Silox,
8
@Nezam to oczekiwane zachowanie. Spróbuj ((TextView)actionBar.getCustomView().findViewById(R.id.textView1)).setText("new title");, gdzie textView1 to Twój TextViewidentyfikator w Twoim CustomView.
Sufian,
8
Jeśli istnieją pozycje menu, nie będą one prawidłowo wyśrodkowane. Aby naprawdę zawsze mieć wyśrodkowany tytuł, dodaj „WRAP_CONTENT” do LinearLayout i przenieś android: layout_gravity = „center” z TextView do LinearLayout.
DominicM
35

Nie odniosłem wielkiego sukcesu z innymi odpowiedziami ... poniżej jest dokładnie to, co działało dla mnie na Androidzie 4.4.3 przy użyciu ActionBar w bibliotece wsparcia v7. Mam ustawione wyświetlanie ikony szuflady nawigacji („przycisk menu burgera”)

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>

Jawa

//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);
Ktoś gdzieś
źródło
Dlaczego musimy stworzyć paramsobiekt? Czy nie możemy określić grawitacji w zewnętrznym pliku układu, który przypisujemy do ActionBar.
Deep Lathia
10

Zdefiniuj swój własny widok z tekstem tytułu, a następnie przekaż LayoutParams do setCustomView (), jak mówi Sergii.

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

EDYTOWANE : Przynajmniej w przypadku szerokości należy użyć WRAP_CONTENT lub szuflady nawigacji, ikony aplikacji itp. NIE BĘDZIE POKAZANA (widok niestandardowy wyświetlany u góry innych widoków na pasku akcji). Dzieje się tak zwłaszcza wtedy, gdy nie jest wyświetlany żaden przycisk akcji.

EDYTOWANO : Odpowiednik w układzie 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">

Nie wymaga to określenia LayoutParams.

actionBar.setCustomView(getLayoutInflater().inflate(R.layout.action_bar_home, null);
ypresto
źródło
8

Tylko szybki dodatek do odpowiedzi Ahmada. Nie możesz już używać getSupportActionBar (). SetTitle, gdy używasz widoku niestandardowego z TextView. Aby więc ustawić tytuł, gdy masz wiele działań z tym niestandardowym ActionBar (używając tego jednego XML), w metodzie onCreate () po przypisaniu niestandardowego widoku:

TextView textViewTitle = (TextView) findViewById(R.id.mytext);
textViewTitle.setText(R.string.title_for_this_activity);
Jordy
źródło
4

DOBRZE. Po wielu badaniach, w połączeniu z zaakceptowaną odpowiedzią powyżej, znalazłem rozwiązanie, które działa również, jeśli masz inne rzeczy na pasku akcji (przycisk Wstecz / Strona główna, przycisk menu). Więc zasadniczo umieściłem metody override w działaniu podstawowym (które rozszerzają wszystkie inne działania) i umieściłem tam kod. Ten kod ustawia tytuł każdego działania, tak jak jest dostarczony w AndroidManifest.xml, a także wykonuje inne niestandardowe rzeczy (takie jak ustawienie niestandardowego odcienia przycisków paska akcji i niestandardowej czcionki w tytule). Musisz tylko pominąć grawitację w action_bar.xml i zamiast tego użyć dopełnienia.actionBar != nullcheck jest używany, ponieważ nie wszystkie moje działania go mają.

Testowane na 4.4.2 i 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);
} ...

A mój action_bar.xml wygląda tak (jeśli ktoś jest zainteresowany):

<?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>

EDYCJA : Jeśli chcesz zmienić tytuł na inny PO załadowaniu działania (zostało już wywołane onCreateOptionsMenu), umieść inny TextView w swoim action_bar.xml i użyj poniższego kodu, aby „dopełnić” ten nowy TextView, ustawić tekst i pokazać to:

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

EDYCJA (25.08.2016) : To nie działa z wersją appcompat 24.2.0 (sierpień 2016), jeśli twoja aktywność ma „przycisk Wstecz”. Złożyłem raport o błędzie ( wydanie 220899 ), ale nie wiem, czy będzie to przydatne (wątpię, że zostanie to naprawione w najbliższym czasie). Tymczasem rozwiązaniem jest sprawdzenie, czy klasa dziecka jest równa AppCompatImageButton.class i zrób to samo, zwiększ szerokość tylko o 30% (np. AppCompatImageButton.getWidth () * 1.3 przed odjęciem tej wartości od oryginalnego wypełnienia):

padding -= appCompatImageButton.getWidth()*1.3;

W międzyczasie wrzuciłem tam kilka sprawdzeń dopełnienia / marginesów:

    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;
        }
    }
W razie czego
źródło
4

bez customview może wyśrodkować tytuł paska akcji. doskonale działa również w szufladzie nawigacji

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

Miłego kodowania. Dziękuję Ci.

Dinithe Pieris
źródło
3

Po wielu badaniach: To faktycznie działa:

 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;

Musisz zdefiniować układ custom_actionbar.xml zgodny z wymaganiami, np .:

<?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>
Roshan Ramtel
źródło
Proste i działa! quotehd.com/imagequotes/authors39/tmb/ ...
AndrewBramwell
@AndrewBramwell getActionBar (). SetDisplayOptions (ActionBar.DISPLAY_SHOW_CUSTOM); rzuca wyjątek zerowy
Ruchir Baronia
Wiecie, jak mogę to naprawić?
Ruchir Baronia
3

Ładnie działa.

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

Poniżej układ paska niestandardowego:

<?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>
Vlad
źródło
2

Musisz ustawić ActionBar.LayoutParams.WRAP_CONTENTiActionBar.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 );
曲 连 强
źródło
„Ustawiłem ActionBar.LayoutParams…” - to nie ma sensu. Sformatuj również kod.
sashoalm
Hah, plz nie bić曲连强, jego przykład setDisplayOptions pomaga mi dodać wyśrodkowany tytuł i Pokaż przycisk strony startowej
djdance
Co to jest „R.layout.action_bar_title”? Nie mogę tego znaleźć.
Jose Manuel Abarca Rodríguez
Co to jest „R.layout.action_bar_title”? Wyjaśnić. Czy muszę zarejestrować ten niestandardowy plik XML w pliku manifestes.xml
Ajay Kulkarni
2

Najlepszy i najłatwiejszy sposób, szczególnie dla tych, którzy chcą po prostu wyświetlać tekst ze środkiem ciężkości bez żadnego układu 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);
turbandroid
źródło
sprawdź motyw aplikacji !!
turbandroid
2

Kod tutaj pracuje dla mnie.

    // 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);
}
Do Xuan Nguyen
źródło
2

Jedyne rozwiązanie Kotlin, które nie wymaga zmian w układach XML:

//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
}
Stanislas Heili
źródło
2

Oto kompletne rozwiązanie Kotlin + androidx, oparte na odpowiedzi od @Stanislas Heili. Mam nadzieję, że przyda się innym. Dotyczy to przypadku, gdy masz działanie, które zawiera wiele fragmentów, przy czym tylko jeden fragment jest aktywny w tym samym czasie.

W Twojej działalności:

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

W twoich fragmentach:

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

    activity?.title = "some title for fragment"
}
Per Christian Henden
źródło
0

Inne samouczki, które widziałem, zastępują cały układ paska akcji, ukrywając MenuItems. Udało mi się to zrobić, wykonując następujące kroki:

Utwórz plik xml w następujący sposób:

<?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>

A w klasie zrób to:

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");
Leonardo Cardoso
źródło
to nie działa - może dlatego, że wyświetla się przycisk menu nawigacji?
Someone Somewhere
0

Dla użytkowników Kotlin:

Użyj następującego kodu w swojej aktywności:

// 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))

I układ XML / zasobów:

<?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>
Maihan Nijat
źródło
-1

Ten kod nie ukryje przycisku wstecz, w tym samym czasie wyrówna tytuł do środka.

wywołaj tę metodę w 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);
    }
}
Gurumoorthy Arumugam
źródło
java.lang.NullPointerException;)
Khan