大佬教程收集整理的这篇文章主要介绍了无法从静态上下文引用非静态方法’getSharedPreferences(java.lang.String,int)’,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个应用程序,我试图将按钮点击次数限制为五次,然后一旦用户按下此按钮五次,它应该禁用.
但是我收到了上述错误,我不知道为什么.
有任何想法吗 ?
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(),这就是它给出编译时错误的原因.
如果该代码在Activity中,请替换
Context.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
同
getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
如果它在片段中,请使用
getActivity().getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
编辑:
使用
if (clicks >= 5){
buttonadd.setEnabled(false);
buttonadd.setClickable(false);
buttonadd.setFocusable(false);
buttonadd.setFocusableInTouchMode(false);
}
privatE int clicks;
在活动中.
编辑2:
int clicks = 0;
同
SharedPreferences prefs = getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int clicks = prefs.geTint("clicks", 0);
试试这个.这应该做到这一点.
以上是大佬教程为你收集整理的无法从静态上下文引用非静态方法’getSharedPreferences(java.lang.String,int)’全部内容,希望文章能够帮你解决无法从静态上下文引用非静态方法’getSharedPreferences(java.lang.String,int)’所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。