当前位置:   article > 正文

初学者在android studio小猴子摘桃点击去桃园按钮直接退出的问题_在android studio的cn.itcast.pickpeach包中创建一个peachacti

在android studio的cn.itcast.pickpeach包中创建一个peachactivity,并将布局

在 android studio2023.2.1 版本实战演练—小猴子摘桃中,按照给出的代码编译运行是没有问题的,但是仿真过程中会出现点击“去桃园”也就是“btn_peach”按键程序就会直接退出,一开始我以为是init()函数中startActivityForResult()方法的问题,但是我在更新成registerForActivityResult()方法后还是不行,然后我开始使用事件处理器来查找问题所在,不查不知道一查吓一跳,报错如下:

可以看到误日志显示了在 cn.itcast.pickpeach.MainActivity 中的一个 onClick 事件处理器中调用了 startActivityForResult 方法时出现了 ActivityNotFoundException 异常。这意味着你的应用试图启动一个名为 PeachActivity 的 Activity,但是在 AndroidManifest.xml 文件中没有正确声明这个 Activity。所以就需要在AndroidManifest.xml 文件中声明为:

  1. <activity
  2. android:name=".PeachActivity"
  3. android:exported="true">
  4. <intent-filter>
  5. <action android:name="android.intent.action.MAIN" />
  6. <category android:name="android.intent.category.LAUNCHER" />
  7. </intent-filter>
  8. </activity>

当然AndroidManifest.xml 文件得完整代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools">
  4. <application
  5. android:allowBackup="true"
  6. android:dataExtractionRules="@xml/data_extraction_rules"
  7. android:fullBackupContent="@xml/backup_rules"
  8. android:icon="@mipmap/ic_launcher"
  9. android:label="@string/app_name"
  10. android:roundIcon="@mipmap/ic_launcher_round"
  11. android:supportsRtl="true"
  12. android:theme="@style/Theme.AppCompat.NoActionBar"
  13. tools:targetApi="31">
  14. <activity
  15. android:name=".MainActivity"
  16. android:exported="true">
  17. <intent-filter>
  18. <action android:name="android.intent.action.MAIN" />
  19. <category android:name="android.intent.category.LAUNCHER" />
  20. </intent-filter>
  21. </activity>
  22. <activity
  23. android:name=".PeachActivity"
  24. android:exported="true">
  25. <intent-filter>
  26. <action android:name="android.intent.action.MAIN" />
  27. <category android:name="android.intent.category.LAUNCHER" />
  28. </intent-filter>
  29. </activity>
  30. </application>
  31. </manifest>

其实在课本中就说明了在创建桃园界面时需要在 cn.itcast,pickpeach 包中创建一个PeachActivity,并将布局文件名指定为 activity_peach。只是他没有具体声明在AndroidManifest.xml 文件中也要声明,所以才会产生点击点击去桃园按钮直接退出的问题。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/502274
推荐阅读
相关标签
  

闽ICP备14008679号