连点处理,禁止按钮在短时间内被多次点击

转载请注明出处:http://www.cnblogs.com/cnwutianhao/p/6694072.html 

 

在做App的过程中,当点击某个按钮的时候,如果不做连点处理,会造成按钮在短时间内被点击多次的情况。

为了避免这种情况的发生,我们需要自定义一个抽象类 CustomClickListener 并继 View.OnClickListener

abstract class CustomClickListener implements View.OnClickListener {

    private static final int MIN_CLICK_DELAY_TIME = 1000;    // 设置1秒内只能点击一次

    private long lastClickTime = 0;

    private int id = -1;

    @Override
    public void onClick(View v) {
        long currentTime = Calendar.getInstance().getTimeInMillis();
        int mId = v.getId();
        if (id != mId) {
            id = mId;
            lastClickTime = currentTime;
            onNoDoubleClick(v);
            return;
        }
        if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
            lastClickTime = currentTime;
            onNoDoubleClick(v);
        }
    }

    protected abstract void onNoDoubleClick(View v);

}

 

本文采用Data-Binding框架,So 在build.gradle(Module:app)下面添加

android {
    ...
    dataBinding {
        enabled = true
    }
}

 

将连点处理写入到需要实现的类里面

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding mBinding;

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

        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        mBinding.btn.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                // TODO:你想执行的操作
            }
        });
    }
}

 

布局文件

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.tnnowu.android.perfectclick.MainActivity">

        <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

    </RelativeLayout>

</layout>

posted on 2017-04-11 16:23  Tyhoo_Wu  阅读(2852)  评论(0编辑  收藏  举报

导航