2013年8月

Android View点击频率控制

提交数据操作

代码


/**
 * Created by wangjie on 2015/4/12
 */

public abstract class OnClickWrapperListener implements View.OnClickListener {

    private long MIN_DELAY_TIME = 500L; //default delay time

    private long lastClickTime = 0L;

    public OnClickWrapperListener() {}

    public OnClickWrapperListener(long delayTime) {
        this.MIN_DELAY_TIME = delayTime;
    }

    @Override
    public void onClick(View v) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastClickTime > MIN_DELAY_TIME) {
            lastClickTime = currentTime;
            onWrapperClick(v);
        }
    }

    public abstract void onWrapperClick(View v);
}

使用

        // delay 6000 millis
        targetView.setOnClickListener(new OnClickWrapperListener(6000L) {
            @Override
            public void onWrapperClick(View v) {
                Log.e(TAG, "- onWrapperClick 6000L-");
            }
        });

        // default 500 millis
        targetView.setOnClickListener(new OnClickWrapperListener() {
            @Override
            public void onWrapperClick(View v) {
                Log.e(TAG, "- onWrapperClick -");
            }
        });

测试

04-12 17:30:05.569 13828-13828/com.wangj.sample E/Sample: - onWrapperClick 6000L-
04-12 17:30:11.659 13828-13828/com.wangj.sample E/Sample: - onWrapperClick 6000L-
04-12 17:30:17.749 13828-13828/com.wangj.sample E/Sample: - onWrapperClick 6000L-
04-12 17:30:29.429 13828-13828/com.wangj.sample E/Sample: - onWrapperClick 6000L-

Android 双击返回键退出应用程序

long mExitTime = 0L;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (KeyEvent.KEYCODE_BACK == keyCode) {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            toast("再按一次退出程序");
            // 将系统当前的时间赋值给exitTime
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}