如何在Android中居中对齐ActionBar标题?

时间:2012-09-12 11:40:00

标签: android android-actionbar android-theme

我正在尝试使用以下代码将文本居中放在ActionBar中,但它会将自己对齐到左侧。

如何让它出现在中心?

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

18 个答案:

答案 0 :(得分:188)

要在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="match_parent"
    android:layout_height="wrap_content"
    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:layout_gravity="center"
        android:gravity="center"
        android:textColor="#FFFFFF" />

</LinearLayout>

现在你应该只拥有一个Actionbar标题。如果要设置自定义背景,请在上面的布局中进行设置(但不要忘记设置android:layout_height="match_parent")。

或与:

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

答案 1 :(得分:34)

我对其他答案没有取得多大成功......以下是使用支持库v7中的ActionBar在Android 4.4.3上对我有用的功能。我将其设置为显示导航抽屉图标(&#34;汉堡菜单按钮&#34;)

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

答案 2 :(得分:9)

使用标题文本定义自己的自定义视图,然后将LayoutParams传递给setCustomView(),如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
        )
);

已编辑:至少对于宽度,您应该使用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);

答案 3 :(得分:8)

只是艾哈迈德回答的快速补充。使用带TextView的自定义视图时,不能再使用getSupportActionBar()。setTitle。因此,当您使用此自定义ActionBar(使用此xml)进行多个活动时设置标题,请在onCreate()方法 后指定自定义视图:

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

答案 4 :(得分:4)

行。经过大量的研究,结合上面接受的答案,我提出了一个解决方案,如果你的操作栏中有其他东西(后退/主页按钮,菜单按钮),它也可以工作。所以基本上我已经将覆盖方法放在基本活动中(所有其他活动都扩展),并将代码放在那里。此代码设置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),请在action_bar.xml中添加另一个TextView并使用以下代码“填写“这个新的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);
    }
}

编辑(2016年8月25日):如果您的活动有“后退按钮”,则不适用于appcompat 24.2.0修订版(2016年8月)。我提交了一份错误报告(Issue 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;
        }
    }

答案 5 :(得分:4)

没有自定义视图,它能够集中操作栏标题。 它完美适用于导航抽屉

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

快乐的编码。谢谢。

答案 6 :(得分:3)

经过大量研究后: 这实际上有效:

 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>

答案 7 :(得分:3)

效果很好。

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>

答案 8 :(得分:2)

这是一个完整的Kotlin + androidx解决方案,基于@Stanislas Heili的回答。我希望它可能对其他人有用。当您拥有一个托管多个片段的活动时,只有一个片段同时处于活动状态。

在您的活动中:

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

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

在您的片段中:

package.json

答案 9 :(得分:1)

您需要设置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 );

答案 10 :(得分:1)

最好,最简单的方法,特别适合那些只希望使用重力中心而不使用任何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);

答案 11 :(得分:1)

仅Kotlin的解决方案,不需要在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
}

答案 12 :(得分:1)

以下是使动作居中对齐的快速提示:

android:label=" YourTitle"

假设您已启用操作栏,则可以在活动中添加一些空格(可以调整)以将标题放置在中心。

但是,这只是愚蠢和不可靠的方法。您可能不应该这样做。因此,最好的办法是创建一个自定义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相同。

答案 13 :(得分:0)

此代码不会隐藏后退按钮,同时将标题对齐中心。

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

答案 14 :(得分:0)

我见过的其他教程覆盖了隐藏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>

在classe中做到了:

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

答案 15 :(得分:0)

对于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>

答案 16 :(得分:0)

代码here为我工作。

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

答案 17 :(得分:0)

我的解决方案是将工具栏的文本部分分开,以定义样式并说出居中或对齐方式。可以用XML本身完成。当您执行总是可见的操作时,可以在计算后指定一些填充。我已将两个属性从工具栏移至其子TextView。可以提供此textView的ID,以便从片段中访问。

[
  [
    0, 1, 2, 3,
    4, 4, 4, 4
  ],
  [
    5,  6,  7,  8,
    9, 10, 11, 11
  ],
  [ 12 ],
  [ 14 ]
]
相关问题