本文介绍了未解决的参考:getPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图存储一个布尔值,该值每次单击按钮时都会更改.我想使用共享的首选项来执行此操作,但是我一直遇到此错误: 无法解析的参考:getPreferences

I am trying to store a boolean value which is changed every time a button is clicked. I want to do this using shared preferences, however I keep running into this error: Unresolved reference: getPreferences

这是我的代码:

btnStyle.setOnClickListener() {
            styleHasChanged = !styleHasChanged;

            if(styleHasChanged  == true){
                btnStyle.setText("true")
            }else{
                btnStyle.setText("false")
            }

          //  AppUtil.saveConfig(activity, config)
          //  EventBus.getDefault().post(ReloadDataEvent())

          var sharedPref : SharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
            var editor = sharedPref.edit()
            editor.putBoolean("bla", styleHasChanged)
            editor.commit()



        }

推荐答案

这是Fragment还是Activity?这似乎是用片段或其他地方编写的代码.因为getPreferences()是活动的方法,您需要具有活动的实例才能调用它.

Is this a Fragment or an Activity? This seems code written in fragment or somewhere else. Because getPreferences() is method of activity and you need to have Activity's instance to call it .

只有一个Activity实例,并按如下所示对其进行调用.片段的示例:-

Just have a Activity instance and call it as below . example for Fragment:-

btnStyle.setOnClickListener() {
        styleHasChanged = !styleHasChanged;
        if(styleHasChanged  == true){
            btnStyle.setText("true")
        }else{
            btnStyle.setText("false")
        }
        val sharedPref : SharedPreferences?= activity?.getPreferences(Context.MODE_PRIVATE);
        sharedPref?.edit()?.putBoolean("bla", styleHasChanged)?.apply()
    }

这篇关于未解决的参考:getPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-24 23:14