声明 CheckBoxPreference 时无法成功转换

Unsucceedable cast when declaring CheckBoxPreference

在我的 activity 中为我的应用程序设置声明 CheckboxPreference 后,在“val mCheckBoxPreference = findPreference("preference_a") as CheckBoxPreference”行中出现 as 的警告。应该怎么做才能使转换成功?

This cast can never succeed

app_preferences.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <CheckBoxPreference
        android:key="preference_a"
        android:defaultValue="false"
        android:title="Preference A"/>

</PreferenceScreen>

片段class

import android.content.Context
import android.os.Bundle
import android.preference.CheckBoxPreference
import android.preference.Preference
import android.support.v7.preference.PreferenceFragmentCompat
import android.util.Log

class MySettingsFragment : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener {
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        addPreferencesFromResource(R.xml.app_preferences)

        val mCheckBoxPreference = findPreference("preference_a") as CheckBoxPreference
        mCheckBoxPreference.onPreferenceChangeListener = this
    }

    // declaring PreferenceXchangeListener
    private var mPreferenceXchangeListener: PreferenceXchangeListener? = null

    // declaring PreferenceXchangeListener in order to communicate with Activities
    interface PreferenceXchangeListener {
        fun onXchange(value:Boolean)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        // on attach - assign parent Activity as PreferenceXchangeListener
        try
        {
            mPreferenceXchangeListener = context as MySettingsFragment.PreferenceXchangeListener
        }
        catch (e:ClassCastException) {
            Log.e(TAG, "onAttach::::: PreferenceXchangeListener must be set in parent Activity")
        }
    }

    override fun onPreferenceChange(preference: Preference, newValue:Any):Boolean {
        val preferenceKey = preference.key

        if (preferenceKey == "preference_a")
        {
            (preference as CheckBoxPreference).isChecked = newValue as Boolean
            // executing parent Activity's callback with the new value
            mPreferenceXchangeListener!!.onXchange(newValue)
            return true
        }
        return false
    }

    companion object {
        private val TAG = MySettingsFragment::class.java.simpleName
    }
}

activity class

class MySettingsActivity : AppCompatActivity(), MySettingsFragment.PreferenceXchangeListener {
    private var mCurrentValue: Boolean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        val mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
        mCurrentValue = mSharedPreferences.getBoolean("preference_a", false)
        if (mCurrentValue as Boolean)
        {
            setTheme(R.style.MyDarkAppCompatTheme)
        }
        else
        {
            setTheme(R.style.MyLightAppCompatTheme)
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mysettings)

        val settingsFragment = MySettingsFragment()
        supportFragmentManager
                .beginTransaction()
                .replace(R.id.settings_container, settingsFragment)
                .commit()

        val myActionBar = actionBar

        if (myActionBar != null)
        {
            myActionBar.setTitle(R.string.settings)                
            myActionBar.setBackgroundDrawable(ColorDrawable(Color.BLACK))
        }
    }

    override fun onXchange(value:Boolean) {
        if (value !== mCurrentValue)
        {
            mCurrentValue = value
            recreate()
        }
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                val intent = parentActivityIntent
                intent?.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                onBackPressed()
                return true
            }

            else ->
                return super.onOptionsItemSelected(item)
        }
    }

    companion object {
        private val TAG = MySettingsActivity::class.java.simpleName
    }
}

TL;DR 您必须将导入更改为 android.support.v7.preference.CheckBoxPreference.

CheckBoxPreference有两个版本:

  • android.preference.CheckBoxPreference,在 API 级别 1 中添加并且具有 android.preference.Preference 作为祖先 class
  • android.support.v7.preference.CheckBoxPreference 属于支持库并且有 android.support.v7.preference.Preference 作为祖先 class

您的 FragmentPreferenceFragmentCompat 延伸而来,因此 findPreference() 将 return 变成 android.support.v7.preference.Preference。由于您无法将 support Preference classes 转换为 non support 等价物,Android Studio当您尝试转换为 不支持 CheckBoxPreference.

时显示错误消息 "This cast can never succeed"