赞
踩
在 android studio2023.2.1 版本实战演练—小猴子摘桃中,按照给出的代码编译运行是没有问题的,但是仿真过程中会出现点击“去桃园”也就是“btn_peach”按键程序就会直接退出,一开始我以为是init()函数中startActivityForResult()方法的问题,但是我在更新成registerForActivityResult()方法后还是不行,然后我开始使用事件处理器来查找问题所在,不查不知道一查吓一跳,报错如下:
可以看到误日志显示了在 cn.itcast.pickpeach.MainActivity
中的一个 onClick
事件处理器中调用了 startActivityForResult
方法时出现了 ActivityNotFoundException
异常。这意味着你的应用试图启动一个名为 PeachActivity
的 Activity
,但是在 AndroidManifest.xml
文件中没有正确声明这个 Activity
。所以就需要在AndroidManifest.xml
文件中声明为:
- <activity
- android:name=".PeachActivity"
- android:exported="true">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
当然AndroidManifest.xml
文件得完整代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools">
-
- <application
- android:allowBackup="true"
- android:dataExtractionRules="@xml/data_extraction_rules"
- android:fullBackupContent="@xml/backup_rules"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:roundIcon="@mipmap/ic_launcher_round"
- android:supportsRtl="true"
- android:theme="@style/Theme.AppCompat.NoActionBar"
- tools:targetApi="31">
- <activity
- android:name=".MainActivity"
- android:exported="true">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <activity
- android:name=".PeachActivity"
- android:exported="true">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
-
- </manifest>
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
其实在课本中就说明了在创建桃园界面时需要在 cn.itcast,pickpeach 包中创建一个PeachActivity,并将布局文件名指定为 activity_peach。只是他没有具体声明在AndroidManifest.xml
文件中也要声明,所以才会产生点击点击去桃园按钮直接退出的问题。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。