具体错误如下代码块所示:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.xmljavalayout, PID: 6313
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xmljavalayout/com.example.xmljavalayout.MainActivity}: java.lang.ClassCastException: androidx.gridlayout.widget.GridLayout cannot be cast to android.widget.GridLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.ClassCastException: androidx.gridlayout.widget.GridLayout cannot be cast to android.widget.GridLayout
at com.example.xmljavalayout.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
出现这种错误的时候程序能运行,但是模拟器中的app会出现闪退,之所以出现这种问题是因为gridlayout不能被转换为android.widget.GridLayout。所以我们对症下药,gridlayout不能转换了是因为包引用的不对,之前是这样子引用的:
后来改为这样:
就能正确运行了。