美文网首页
Android_防止快速点击

Android_防止快速点击

作者: 738bc070cd74 | 来源:发表于2015-12-04 12:02 被阅读414次

重写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_防止快速点击

      本文链接:https://www.haomeiwen.com/subject/ikushttx.html