Android_防止快速点击

重写OnClickListener

public abstract class DebouncingOnClickListener implements View.OnClickListener {
private static boolean enabled = true;

private static final Runnable ENABLE_AGAIN = new Runnable() {
    @Override
    public void run() {
        enabled = true;
    }
};

@Override
public final void onClick(View v) {
    if (enabled) {
        enabled = false;
        v.post(ENABLE_AGAIN);
        doClick(v);
    }
}

public abstract void doClick(View v);
}

模拟点击

txt = (TextView) findViewById(R.id.txt);
    
    /*txt.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this, SecondActivity.class));
        }
    });*/
    txt.setOnClickListener(new DebouncingOnClickListener() {
        
        @Override
        public void doClick(View v) {
            // TODO Auto-generated method stub
            startActivity(new Intent(MainActivity.this, SecondActivity.class));
        }
    });
    for (int i = 0; i < 3; i++) {
        txt.performClick();
    }

使用系统自带的OnClickListener会打开三次SecondActivity,使用DebouncingOnClickListener 则只会打开一次。

你可能感兴趣的:(Android_防止快速点击)