Пользовательский диалог вылетает после смены темы - PullRequest
0 голосов
/ 19 сентября 2019

Я пытаюсь, чтобы мое приложение показывало диалоги, и пока оно работает нормально, за исключением случаев, когда я меняю темы (я использую DayNight).

Мой диалог использует собственный стиль, который также имеетродительский день (Theme.AppCompat.DayNight.Dialog).Когда тема меняется (вручную или автоматически), и я открываю диалог после смены темы, приложение вылетает.

Я получаю сообщение об ошибке NullPointerException.

вот logcat

2019-09-19 13:28:37.721 15733-15733/com.jerrwu.template E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.jerrwu.template, PID: 15733
    kotlin.KotlinNullPointerException
        at com.jerrwu.template.SettingsFragment$onPreferenceChangeListener$1.onSharedPreferenceChanged(SettingsFragment.kt:71)
        at android.app.SharedPreferencesImpl$EditorImpl.notifyListeners(SharedPreferencesImpl.java:607)
        at android.app.SharedPreferencesImpl$EditorImpl.apply(SharedPreferencesImpl.java:489)
        at androidx.preference.Preference.tryCommit(Preference.java:1632)
        at androidx.preference.Preference.persistBoolean(Preference.java:1931)
        at androidx.preference.TwoStatePreference.setChecked(TwoStatePreference.java:92)
        at androidx.preference.TwoStatePreference.onClick(TwoStatePreference.java:68)
        at androidx.preference.Preference.performClick(Preference.java:1182)
        at androidx.preference.Preference.performClick(Preference.java:1166)
        at androidx.preference.SwitchPreference.performClick(SwitchPreference.java:195)
        at androidx.preference.Preference$1.onClick(Preference.java:181)
        at android.view.View.performClick(View.java:6599)
        at android.view.View.performClickInternal(View.java:6576)
        at android.view.View.access$3100(View.java:780)
        at android.view.View$PerformClick.run(View.java:25926)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6718)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

из styles.xml

<style name="DialogTheme" parent="Theme.AppCompat.DayNight.Dialog">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowFrame">@null</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:backgroundTint">@color/colorMain</item>
        <item name="android:windowBackground">@drawable/rounded_dialog_box</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:windowMinWidthMajor">85%</item>
        <item name="android:windowMinWidthMinor">85%</item>
    </style>

кода для отображениядиалог

fun showDialog(title: String, textYes: String, textNo: String, activity: Activity) {
        val dialog = Dialog(activity, R.style.DialogTheme)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setCancelable(false)
        dialog.setContentView(R.layout.custom_dialogue)
        val body = dialog.findViewById(R.id.dialogueBody) as TextView
        body.text = title
        val yesBtn = dialog.findViewById(R.id.yesBtn) as Button
        yesBtn.text = textYes
        val noBtn = dialog.findViewById(R.id.noBtn) as Button
        noBtn.text = textNo
        if (textYes == "") { yesBtn.visibility = View.GONE }
        yesBtn.setOnClickListener {
            dialog.dismiss()
        }
        noBtn.setOnClickListener { dialog.dismiss() }
        dialog.show()

    }

custom_dialogue.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:paddingTop="14dp"
    android:paddingStart="24dp"
    android:paddingEnd="24dp"
    android:paddingBottom="4dp"
    android:layout_height="wrap_content">

    <TextView
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:id="@+id/dialogueBody"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hie..."
        android:textSize="16sp"
        android:textColor="@color/colorFont"
        />

    <Button
        app:layout_constraintTop_toBottomOf="@id/dialogueBody"
        android:layout_marginBottom="0dp"
        android:layout_marginTop="12dp"
        android:textAllCaps="false"
        android:textSize="12sp"
        android:minWidth="40dp"
        android:minHeight="40dp"
        android:id="@+id/yesBtn"
        android:fontFamily="@font/productsansbold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:text="@string/button_yes"
        android:textColor="@color/red"
        android:background="?attr/selectableItemBackground"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        app:layout_constraintTop_toBottomOf="@id/dialogueBody"
        android:layout_marginBottom="0dp"
        android:layout_marginTop="12dp"
        app:layout_constraintEnd_toStartOf="@id/yesBtn"
        app:layout_constraintBottom_toBottomOf="parent"
        android:textSize="12sp"
        android:textAllCaps="false"
        android:minWidth="40dp"
        android:minHeight="40dp"
        android:id="@+id/noBtn"
        android:layout_marginEnd="12dp"
        android:fontFamily="@font/productsansbold"
        android:text="@string/button_no"
        android:textColor="@color/colorAccent"
        android:background="?attr/selectableItemBackground"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</androidx.constraintlayout.widget.ConstraintLayout>

фрагмент, создающий диалог:

class SettingsFragment : PreferenceFragmentCompat() {

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.preferences, rootKey)

        val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)

        val darkToggle = sharedPreferences.getString("dark_toggle", "2")?.toInt()
        val darkPreference = findPreference("dark_toggle") as ListPreference?
        val versionPreference = findPreference("version") as Preference?
        val namePreference = findPreference("name") as EditTextPreference?
        var versionStr = "Error"
        sharedPreferences.registerOnSharedPreferenceChangeListener(onPreferenceChangeListener)

        preferenceScreen.removePreference(namePreference)

        when (darkToggle) {
            -1 -> darkPreference!!.summary = "Follow System"
            0 -> darkPreference!!.summary = "Set by Battery Saver"
            1 -> darkPreference!!.summary = "On"
            2 -> darkPreference!!.summary = "Off"
        }

        try {
            val pInfo = context?.packageManager?.getPackageInfo(activity?.packageName, 0)
            versionStr = pInfo?.versionName.toString()
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        versionPreference!!.summary = versionStr


    }

    var onPreferenceChangeListener: SharedPreferences.OnSharedPreferenceChangeListener =
        SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
            if (key == "dark_toggle") {
                val darkPreference = findPreference(key) as ListPreference?
                val darkToggle = sharedPreferences.getString(key, "2")?.toInt()
                when (darkToggle) {
                    -1 -> {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
                        darkPreference!!.summary = "Follow System"
                    }
                    0 -> {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
                        darkPreference!!.summary = "Set by Battery Saver"
                    }
                    1 -> {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                        darkPreference!!.summary = "On"
                    }
                    2 -> {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                        darkPreference!!.summary = "Off"
                    }
                }
            }
            else if (key == "bottomNavHide") {
                InfoHelper.showDialog("An app restart is recommended after changing this setting.",
                    "", "OK", activity!!)
            }
        }
}

Заранее спасибо всем, кто пытается помочь!

...