setSupportActionBar(myToolbar)导致的程序闪退

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值