我制作了一个应用程序,用户按下一个按钮可以进入另一个 Activity ,但我只希望用户总共按下这个按钮 5 次。我尝试了下面的代码,但是它并没有阻止用户按下按钮超过 5 次,所以我猜应用程序需要以某种方式记住点击次数?
public void FoodClicks(View view){
if(this.counter == 5){
this.counter ++;
}
else {
Button btn = (Button)findViewById(R.id.button);
btn.setEnabled(false);
}
}
ActivityMain.xml:
<Button
android:id="@+id/button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp"
android:text="@string/addmeal" />
最佳答案
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int clicks = 0;
clicks++;
if (clicks >= 5){
button.setEnabled(false);
}
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", this.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("clicks", clicks);
editor.apply();
}
});
使用 sharedPreferences
来存储点击次数,因此如果您的按钮执行任何操作,可以存储点击次数。
关于java - 限制按钮点击次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813092/