非静态方法&x27;getSharedReferences(java.lang.String,int)和#x27;无法从静态上下文引用

非静态方法&x27;getSharedReferences(java.lang.String,int)和#x27;无法从静态上下文引用,java,android,android-studio,android-view,android-button,Java,Android,Android Studio,Android View,Android Button,我有一个应用程序,我正在尝试将按钮点击次数限制为5次,然后一旦用户按下此按钮5次,它就会被禁用 然而,我得到上述错误,我不知道为什么 有什么想法吗 buttonadd.setOnClickListener(new OnClickListener () { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationCo

我有一个应用程序,我正在尝试将按钮点击次数限制为5次,然后一旦用户按下此按钮5次,它就会被禁用

然而,我得到上述错误,我不知道为什么

有什么想法吗

          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();

        }

    });

正如错误消息所说,
getSharedReferences()
是一种非静态方法。执行
Context.getSharedReferences(…)
时,您试图直接从类调用它。相反,您需要从
上下文
实例调用它

如果您的代码位于
活动
(作为
活动
扩展
上下文
)中,您只需执行以下操作:

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

这意味着您需要一个
Context
对象的实例来调用
getSharedReferences()
方法。如果您在
活动中
,请尝试以下操作:

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

您错误地试图以静态方式使用虚拟方法
getSharedReferences()
,这就是为什么它会给出编译时错误

如果该代码位于
活动中
,请更换

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

如果它位于
片段中
,请使用

getActivity().getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
编辑:

使用

并使
单击
成为类成员,即将其声明为

private int clicks;
活动中

编辑2:

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

int clicks = 0;


试试这个。这应该行。

行了,谢谢。但是,当我对它进行测试时,它仍然允许用户按下按钮5次以上,我不知道为什么…不需要调用
getApplicationContext()
。只要调用
getSharedReferences()
就可以了。如果它是RecyclerView的适配器类呢?我们如何实现SharedReference?谢谢advanceThanks,我改变了这一点,它成功了。但是,当我测试它时,它仍然允许我单击按钮5次以上…现在,我会告诉你。它仍然允许单击按钮5次以上。
clicks
始终为1,因为每次单击后,您都会创建一个新的
clicks
设置为0,然后将其递增为1。如果将clicks变量移动到类中,它将起作用。没有必要储存它。你需要回顾一下你对变量作用域和现存变量的理解。@pzulw:虽然你是对的,但我认为他想要的是按钮应该可以点击5次,这就是他使用
共享引用的原因。我建议编辑2以便正确工作:)
private int clicks;
int clicks = 0;
SharedPreferences prefs = getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int clicks = prefs.getInt("clicks", 0);