首页 > 解决方案 > 为什么我在 Kotlin 中使用委托时 isBackgroundWindow 返回错误?

问题描述

我希望为 var 设置一个值isBackgroundWindow,但private var isBackgroundWindow: Boolean by PreferenceTool(this@UIHome, getString(R.string.IsBackgroundName) , false)导致 null 错误,为什么?

顺便说一句,代码 0代码 1是错误的。

代码 0

   private lateinit  var isBackgroundWindow: Boolean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_home)  

        isBackgroundWindow= PreferenceTool(this, getString(R.string.IsBackgroundName) , false)
    }

代码 1

private var isBackgroundWindow: Boolean by lazy {
        PreferenceTool<Boolean>(this@UIHome, getString(R.string.IsBackgroundName), false)
    }

代码 A

class UIHome : AppCompatActivity() {
    private var isBackgroundWindow: Boolean by PreferenceTool(this@UIHome, getString(R.string.IsBackgroundName) , false)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_home)
        isBackgroundWindow=true
    }
}

代码 B

class PreferenceTool<T>(private val context: Context, private val name: String,  private val default: T) {

    private val prefs: SharedPreferences by lazy {      
        context.defaultSharedPreferences     
    }

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default)

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPreference(name, value)
    }

    @Suppress("UNCHECKED_CAST")
    private fun findPreference(name: String, default: T): T = with(prefs) {
        val res: Any = when (default) {
            is Long -> getLong(name, default)
            is String -> getString(name, default)
            is Int -> getInt(name, default)
            is Boolean -> getBoolean(name, default)
            is Float -> getFloat(name, default)
            else -> throw IllegalArgumentException("This type can be saved into Preferences")
        }

        res as T
    }

    @SuppressLint("CommitPrefEdits")
    private fun putPreference(name: String, value: T) = with(prefs.edit()) {
        when (value) {
            is Long -> putLong(name, value)
            is String -> putString(name, value)
            is Int -> putInt(name, value)
            is Boolean -> putBoolean(name, value)
            is Float -> putFloat(name, value)
            else -> throw IllegalArgumentException("This type can't be saved into Preferences")
        }.apply()
    }
}

标签: androidkotlin

解决方案


推荐阅读