2017年特意写第一篇博客开个头。之前一直不写博客的原因,一个是懒,另一个是因为觉得自己没那个能力,会误导别人。但是最近特别想听听别人的意见,所以就下定决心开始写博客。废话不说,赶快开波。
前言
用过Toolbar的都知道标题是在左边的,但通常UI都要求我们把标题居中。没用过的童鞋可以看看泡网的一篇文章android:ToolBar详解(手把手教程)。我并不想自己写一个布局来充当Toolbar,因为那样会增加不少工作量。但怎样才能把Toolbar的标题居中?
有问题先google。如果你还在百度的话,我也没什么办法了。谷歌后找到这样一种方法。在原来的Toolbar里面加上一个TextView,标题居中的关键是第12行,将layout_gravity设置成center。
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary">
<TextView
android:id="@+id/toolbar_title"
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</android.support.v7.widget.Toolbar>
接着再来个helper类。很简单的一个类,看看init方法就可以过了。
public class ToolbarHelper {
private TextView mTitleTextView;
private Toolbar mToolbar;
public void init(AppCompatActivity activity, Toolbar toolbar, TextView titleTextView) {
if (activity == null) {
return;
}
mTitleTextView = titleTextView;
mToolbar = toolbar;
activity.setSupportActionBar(toolbar);
// titleTextView不为null才设置actionbar不显示Title
if (titleTextView != null) {
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
// 不显示title和subTitle
actionBar.setDisplayShowTitleEnabled(f