如何在中间设置ActionBar标题而不是默认的左对齐位置?

尝试将ActionBar标题设置在中间而不是默认的左对齐位置。 为此,基于其他答案,这就是我所做的:

  Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbarDownloads); setSupportActionBar(myToolbar); if(getSupportActionBar()!=null) { getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.actionbar_layout); } 

actionbar_layout.xml

      

但是,这不会产生预期的结果(即,这会使文本仍然保持对齐) ,这种方法有什么问题以及如何解决这个问题?

试试这个使用自定义Toolbar

      

现在在java文件中

 private Toolbar toolbar; toolbar = (Toolbar) findViewById(R.id.ar_toolbar); TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title); mTitle.setText("Nilesh Rathod"); setSupportActionBar(toolbar); 

简单方法在TextView上使用android:layout_gravity="center" ,并在初始化TextView并设置值后使用下面的代码隐藏默认标题

在您的活动中:

 setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); toolbar_title = (TextView) findViewById(R.id.toolbar_title); toolbar_title.setText("My Custom center title"); 

自定义工具栏XML代码:

     

您需要在xml文件中使用Toolbar ,并且可以在Toolbar使用TextView 。 您可以将自定义视图添加到Toolbar 。 完成xml文件后,可以将Toolbar定义为Activity类。

     //Rest of your code  

在Activity类中,您可以定义为

 Toolbar toolbar; toolbar = (Toolbar) findViewById(R.id.ar_toolbar); toolbar.setTitle(""); 

您不需要Toolbar 。 只需在您的活动中使用Theme.AppCompat.Light.DarkActionBar主题和ActionBar ,并使用以下代码:

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.actionbar_layout); } //your code }