标签:android java android-studio android-view android-button
我有一个应用程序,我试图将按钮点击次数限制为五次,然后一旦用户按下此按钮五次,它应该禁用.
但是我收到了上述错误,我不知道为什么.
有任何想法吗 ?
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);
试试这个.这应该做到这一点.
标签:android,java,android-studio,android-view,android-button 来源: https://codeday.me/bug/20190728/1559212.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。