Activity切换后App崩溃求助:启动页跳转主页面异常
刚接触Android开发遇到这种崩溃很正常,咱们直接从LogCat的错误信息入手——它已经把问题说得明明白白啦!
先看核心错误提示:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.benf.myapplication/com.example.benf.myapplication.MainActivity}: java.lang.IllegalStateException: 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.
问题根源
你的启动页SplashScreen用了@style/AppTheme.NoActionBar主题(无系统自带ActionBar),但MainActivity默认继承了全局的AppTheme(这个主题是自带系统ActionBar的)。如果MainActivity的布局里加了自定义Toolbar,或者你在代码里尝试配置Toolbar,就会和系统自带的ActionBar产生冲突,直接导致崩溃。
两种可行的解决方案
方案一:给MainActivity单独设置无ActionBar主题
直接在Manifest里修改MainActivity的配置,加上无ActionBar的主题:
<activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar"/>
这样MainActivity就不会加载系统ActionBar,和你的布局/代码逻辑匹配。
方案二:全局修改主题禁用ActionBar(适合全App用自定义Toolbar的场景)
打开res/values/styles.xml,修改全局的AppTheme,禁用系统ActionBar:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- 保留你原有的其他主题属性 --> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style>
这样所有继承AppTheme的Activity都会默认关闭系统ActionBar,你可以在任意页面自由添加自定义Toolbar。
额外小优化:避免启动页内存泄漏
你当前用Thread.sleep()做延时跳转的方式有内存泄漏风险(比如用户在3秒内返回退出启动页,线程还会持有Activity引用),推荐改用Handler.postDelayed:
import android.content.Intent; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class SplashScreen extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); new Handler(Looper.getMainLooper()).postDelayed(() -> { Intent intent = new Intent(SplashScreen.this, MainActivity.class); startActivity(intent); finish(); }, 3000); } }
内容的提问来源于stack exchange,提问作者Kali Ma

