【问题标题】:Android - How to launch custom DialogPreference from MainActivity?Android - 如何从 MainActivity 启动自定义 DialogPreference?
【发布时间】:2018-06-10 20:23:57
【问题描述】:

我想使用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)
    }
}

我现在其实很困惑,因为我阅读了一些关于如何创建这些设置菜单的教程。我的第一种方法是PreferenceActivity,它使用PreferenceFragment

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 Studio没有给我选择SettingsActivity的选项(可能是因为它实际上没有Activity)

标签: android kotlin settings preferences


【解决方案1】:

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

【讨论】:

  • 感谢您的回答 - 但让我问这个问题:如果不是 Activity,我什至如何使用 DialogPreference
  • 自定义你只扩展 DialogPreference 到一个新类,并在你的 xml 首选项布局中使用这个类。这是一个很好的教程[链接][mysoftdevs.blogspot.com.eg/2011/12/…
  • 但是我现在如何处理我的preference.xml?如何使用/显示它?
  • PreferenceFragment 不是Activity 的子类并且不被视为活动,因此使类扩展PreferenceFragment 并在onCreate 中添加preference.xml .... 再创建一个新类扩展DialogPreference 并在preference.xml 中使用此类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-18
  • 1970-01-01
  • 2014-10-30
  • 2018-01-01
相关资源
最近更新 更多