连点处理,禁止按钮在短时间内被多次点击
转载处:http://www.cnblogs.com/cnwutianhao/p/6694072.html
在做App的过程中,当点击某个按钮的时候,如果不做连点处理,会造成按钮在短时间内被点击多次的情况。
为了避免这种情况的发生,我们需要自定义一个抽象类 CustomClickListener 并继 View.OnClickListener
1 abstract class CustomClickListener implements View.OnClickListener { 2 3 private static final int MIN_CLICK_DELAY_TIME = 1000; // 设置1秒内只能点击一次 4 5 private long lastClickTime = 0; 6 7 private int id = -1; 8 9 @Override 10 public void onClick(View v) { 11 long currentTime = Calendar.getInstance().getTimeInMillis(); 12 int mId = v.getId(); 13 if (id != mId) { 14 id = mId; 15 lastClickTime = currentTime; 16 onNoDoubleClick(v); 17 return; 18 } 19 if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) { 20 lastClickTime = currentTime; 21 onNoDoubleClick(v); 22 } 23 } 24 25 protected abstract void onNoDoubleClick(View v); 26 27 }
将连点处理写入到需要实现的类里面
1 /** 2 * 3 * 控件中有一个按钮,一秒只能点击一次生效 4 * 5 */ 6 public class MainActivity extends AppCompatActivity { 7 8 private Button button1; 9 10 @Override 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.activity_main); 14 15 button1 = (Button)findViewById(R.id.button1); 16 17 button1.setOnClickListener(new CustomClickListener(){ 18 @Override 19 protected void onNoDoubleClick(View v) { 20 Log.d("xiazhenjie","click\n\n"); 21 } 22 }); 23 } 24 }