setSupportActionBar(myToolbar)导致的程序闪退
最近在做一个项目,使用了第三方的开源项目,主要是想实现android5.0之后推出的MaterialDesign的风格,但是代码已经写好了,发现一运行就闪退,所以就开始debug,发现问题出现在
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
很显然应该是在第二行出错了,再根据logcat上的日志:
This Activity already has an action bar supplied by the window decor.
Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
所以应当是与activity中的ActionBar有冲突,最后尝试多次知道,是要在清单文件中设置activity的style
(只要有用到这一行代码的activity都需要在该activity节点下定义style),可以按照如下设置
这里指的就是第三行了,这样就不会造成程序崩溃了。
android:theme="@style/MaterialDrawerTheme.Light.DarkToolbar"
关于style部分,
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<declare-styleable name="SlidingPaneLayout">
<attr name="overhangSize" format="dimension" />
</declare-styleable>
<style name="Toolbar.MUHe" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
关于activity_main.xml部分
<androidx.appcompat.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:elevation="4dp"
app:theme="@style/AppTheme"
app:popupTheme="@style/CustomPopupTheme"/>
注意:
1.Toolbar支持的minSdkVersion 最小为21
2.style样式可以参照上面的自己写个更完美的
3.我的androidstudio版本为4.0.1,
gradle-wrapper:gradle-6.1.1-all.zip
我参考了两篇文章,附上链接:
https://www.cnblogs.com/ghylzwsb/p/5845619.html
https://blog.csdn.net/qq_32204197/article/details/78490691