【TabLayout报错】Error inflating class com.google.android.material.tabs.TabLayout
报错现象
当我点击跳转到使用TabLayout的界面,APP会直接崩掉。
报错log
FATAL EXCEPTION: main
Process: com.example.yizeapp118, PID: 6520
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.yizeapp118/com.example.yizeapp118.activity.tab.TabActivity}: android.view.InflateException: Binary XML file line #10: Binary XML file
line #10: Error inflating class com.google.android.material.tabs.TabLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2958)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3093)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1823)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6825)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
Caused by: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class com.google.android.material.tabs.TabLayout
Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class com.google.android.material.tabs.TabLayout
解决方案
去github搜到的方案,给TabLayout添加一个android:theme="@style/Theme.AppCompat.Light.NoActionBar
(不太明白为啥偏偏我要加这条,TabLayout才能不报错,很多案例并没有这条都能正常运行,知道原因的好哥哥好姐姐请不吝赐教)
改前改后代码对比
改之前
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_tab"
android:layout_width="match_parent"
android:layout_height="120dp">
</com.google.android.material.tabs.TabLayout>
</LinearLayout>
改之后
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_tab"
android:layout_width="match_parent"
android:layout_height="120dp"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</com.google.android.material.tabs.TabLayout>
</LinearLayout>
成果
再次跳转到TabLayout那页就不会崩溃了