【发布时间】:2021-06-18 09:55:36
【问题描述】:
我目前正在尝试使用 kotlin 在 android studio 上实现设置功能。我引用了这个guide。我正在使用 mac 和外部 android 设备来运行应用程序
但是,我遇到了一个问题,我的应用程序运行成功(打开,应用程序的其他方面运行良好),但每当我尝试点击“设置”选项时就会崩溃。
以下是我的 MainActivity 类中的函数
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.iSettings) {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
}
return super.onOptionsItemSelected(item)
}
下面是我的 SettingsActivity 类的代码
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
supportFragmentManager
.beginTransaction()
.replace(android.R.id.content, MySettingsFragment())
.commit()
super.onCreate(savedInstanceState)
}
}
下面是 MySettingsFragment 类的代码
class MySettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
}
我的设置/首选项页面的 xml 代码。目前填充了上述指南中的代码示例
<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreferenceCompat
android:key="notifications"
android:title="Enable message notifications"/>
<Preference
android:key="feedback"
android:title="Send feedback"
android:summary="Report technical issues or suggest new features"/>
</androidx.preference.PreferenceScreen>
另外,我的菜单 xml 代码
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/iSettings"
android:orderInCategory="100"
android:title="Settings"
app:showAsAction="never"/>
</menu>
Dropdown menu at top right corner
Settings option which crashes the application
请帮忙!
【问题讨论】:
-
可能是先膨胀片段然后再调用
super.onCreate()导致崩溃。从您的 Logcat 复制堆栈跟踪并在此处添加您的问题。 -
错误是什么?粘贴 logcat 错误,以便我们检查问题。
-
您好,感谢您的回复。将活动添加到清单并更改
super.onCreate()修复它!
标签: android android-studio kotlin android-fragments android-preferences