无法从静态上下文中引用非静态方法 'getSharedPreferences (java.lang.String, int)'

Non-static method 'getSharedPreferences (java.lang.String, int)' cannot be referenced from a static context

我有一个应用程序,我试图将按钮的点击次数限制为五次,然后一旦用户按下此按钮五次,它就应该被禁用。

但是我收到上述错误,我不确定为什么。

有什么想法吗?

          buttonadd.setOnClickListener(new OnClickListener () {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
            startActivity(intent);

            int clicks = 0;
            clicks++;

            if (clicks >= 5){
                buttonadd.setEnabled(false);
            }

            SharedPreferences prefs = Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("clicks", clicks);
            editor.apply();

        }

    });

正如错误消息所说,getSharedPreferences() 是一个非静态方法。当您执行 Context.getSharedPreferences(...) 时,您正在尝试直接从 class 调用它。相反,您需要从 Context 实例调用它。

如果您的代码在 Activity 中(如 Activity 扩展 Context),您可以简单地执行以下操作:

SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);

意思是你需要一个Context对象的实例来调用getSharedPreferences()方法。如果你在 Activity 中,试试这个:

this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE)

您错误地尝试以 static 方式使用 virtual 方法 getSharedPreferences(),这就是它给出编译的原因-时间错误。

如果该代码在 Activity 中,请替换

Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);

getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);

如果在Fragment中,使用

getActivity().getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);

编辑:

使用

if (clicks >= 5){
    buttonadd.setEnabled(false);
    buttonadd.setClickable(false);
    buttonadd.setFocusable(false);
    buttonadd.setFocusableInTouchMode(false);
}

并使 clicks 成为 class 成员,即将其声明为

private int clicks;

Activity.

编辑 2:

我想我已经理解你犯的错误了。在您的代码中,替换

int clicks = 0;

SharedPreferences prefs = getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int clicks = prefs.getInt("clicks", 0);

试试这个。这应该可以做到。