记录在使用Toolbar过程中遇到的各种问题。
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" />
</LinearLayout>
坑一:Toolbar setTitle()方法无效
会默认显示AndroidManifest.xml中当前Activity label标签的文本,如果当前Activity 未设置label标签着向上查找Application label标签的文本,如果Application 未设置label标签,则显示包名。
解决方法:
1.在setSupportActionBar(toolbar);之前调用setTitle()方法。
2.使用getSupportActionBar().setTitle();
3.在onResume()中调用setTitle()方法
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Title");//在setSupportActionBar()前才有效
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.mipmap.ic_format_list_bulleted_white_24dp);
toolbar.setLogo(R.mipmap.ic_launcher);
toolbar.setSubtitle("SubTitle");
}
坑二:Toolbar被系统状态栏覆盖
在layout中添加下列标签即可
android:fitsSystemWindows="true"
坑三:最右的overflow颜色
在参考了Android Studio 创建Blank Activity的Toolbar布局文件后,修改了上面的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:toolbar="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:popupTheme="@style/AppTheme.PopupOverlay" />
</LinearLayout>
</LinearLayout>