限制按钮点击次数 [英] Limit number of button clicks

查看:124
本文介绍了限制按钮点击次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个应用程序,其中用户按下一个按钮以进行另一项活动,但是我只希望用户总共按下该按钮5次.我尝试了以下代码,但是它并没有阻止用户按下按钮超过5次,因此我猜测该应用需要以某种方式记住点击次数?

I have made an app, where the user presses a button to lead onto another activity, but I only want the user to press this button 5 times in total. I tried the below code, however it doesn't stop the user pressing the button more than 5 times, so I'm guessing the app needs to somehow remember the clicks?

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存储点击次数,因此,如果您的按钮执行任何操作,则可以存储点击次数.

Use the sharedPreferences to store number of clicks, so if your button perform any action, clicks can be stored.

这篇关于限制按钮点击次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆