如何每秒将点击量增加1

时间:2014-09-20 07:29:21

标签: java android

所以我一直试图弄清楚如何使当前点击的总量增加 每秒一个。假设点击量为0.每次我点击它都会增加20.但我也希望它每秒上升1。我尝试过使用时间处理程序,我相信我一直在弄乱它。

public class MainActivity extends Activity implements OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String KEY_COUNT = "count";
    private SharedPreferences mPrefs;
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(TAG, "onCreate!");
        mPrefs = getPreferences(MODE_PRIVATE);
        int count = mPrefs.getInt(KEY_COUNT, 0);

        count = count + 1;
        Editor editor = mPrefs.edit();
        editor.putInt(KEY_COUNT, count);
        editor.commit();

        mTextView = new TextView(this);
        setContentView(mTextView);
        mTextView.setTextSize(40);
        mTextView.setText("Count : " + count);
        Log.d(TAG, "Count is " + count);
        setContentView(mTextView);
        //setContentView(R.layout.activity_main);
        mTextView.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }   

    @Override
    public void onClick(View arg0) {
        //  SystemClock.sleep(2000);
        int clickCount = 20 + mPrefs.getInt("clicked", 0);
        mPrefs.edit().putInt("clicked", clickCount).putBoolean("user", true).commit();
        mTextView.setTextColor(0xff00ff00);
        mTextView.setText("The amount of times Lee Ji Eun has clicked:" + clickCount);
    }

}

2 个答案:

答案 0 :(得分:1)

所以你基本上要做的就是每秒将计数器增加1。由于此任务应重复多次,因此您可以使用TimerTask

实施例

Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // Do whatever you wanna do right here (like increasing the clickCount)
            }
        });
    }
};
// scheduleAtFixedRate(TimerTask task, long delay, long period)
timer.scheduleAtFixedRate(timerTask, 0, 1000);

只要未销毁活动或调用Timer.cancel(),就会重复此任务。

答案 1 :(得分:0)

每次点击都会保存当前时间并将其与之前点击的时间相匹配。如果差异等于或大于1秒,则计算该点击否则不要。