Android - 如何从MainActivity启动自定义DialogPreference?

问题描述 投票:0回答:1

我想使用DialogPreference作为我的设置菜单(应用程序屏幕右上方的三个点)。这是我目前的做法:

class SettingsActivity : DialogPreference{
    constructor(context : Context, attrs : AttributeSet) : super(context,attrs){
        isPersistent = false
    }
    override fun onBindDialogView(view: View?) {
        super.onBindDialogView(view)
        (context as Activity).fragmentManager.findFragmentById(R.xml.preferences)
    }
    override fun onDialogClosed(positiveResult: Boolean) {
        super.onDialogClosed(positiveResult)
    }
}

我现在真的很困惑,因为我读了一些关于如何创建这些设置菜单的教程。我的第一个方法是使用PreferenceActivityPreferenceFragment

class SettingsFragment : PreferenceFragment {
    constructor() : super()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        addPreferencesFromResource(R.xml.preferences)
    }
}

我不知道 - 在DialogPreference的情况下我是否也必须使用它?我的preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">

    <com.test.view.DialogExPreference
        android:title="Title"
        android:dialogMessage="Dialog Message"
        android:negativeButtonText="test"/>
</PreferenceScreen>

我尝试像这样启动自定义DialogPreference:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        R.id.action_settings -> {
            var i = Intent(this,SettingsActivity::class.java)
            startActivity(i)
            return true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

但我得到这个错误:

android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.standardbenutzer.integrate/com.example.standardbenutzer.integrate.SettingsActivity}; have you declared this activity in your AndroidManifest.xml?

但如果我尝试将它添加到我的AndroidManifest.xml中 - android:name=".SettingsActivity"没有可用的选项 - 为什么会这样?

android kotlin settings preferences
1个回答
1
投票

你的SettingsActivity扩展DialogPreferenceDialogPreference不被认为是活动,不能在清单中作为活动使用或定义,因为它不是Activity类的子类你可以使用Activity - AppCompatActivity -ActionBarActivity - FragmentActivityActivity.class的任何子类

© www.soinside.com 2019 - 2024. All rights reserved.