简体   繁体   中英

Android - How to launch custom DialogPreference from MainActivity?

I would like to use a DialogPreference as my Settings Menu (the three dots at the upper right at the screen of an App). This is my current approach:

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)
    }
}

I am actually quite confused now, because I read some tutorials about how to create these settings menus. My first approach was a PreferenceActivity which uses a PreferenceFragment :

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

I don't know - do I have to use this in the case of a DialogPreference too? My 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>

I try to start my custom DialogPreference like this:

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)
    }
}

But I get this error:

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?

But if I try to add it to my AndroidManifest.xml - there is no option available for android:name=".SettingsActivity" - why is that?

Your SettingsActivity extendes DialogPreference . DialogPreference is not recognized as activity and can't be used or defined in manifest as activity because it's not subclasses of the Activity class You can use Activity - AppCompatActivity - ActionBarActivity - FragmentActivity or any subclass of Activity.class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM