在开发的过程中收集整理的,绝对超实用
1、CountDown.java 可以用来用作发验证码的倒计时用
public class CountDown implements Runnable {
private TextView textView;
private String countDownText;
private String defaultText;
private int remindSecond = 60;
private Handler handler;
private OnCountDownListener countDownListener;
public CountDown(TextView textView, String countDownText, int remindSecond) {
this.textView = textView;
this.countDownText = countDownText;
this.remindSecond = remindSecond;
defaultText = textView.getText().toString();
handler = new Handler();
}
/**
* 开始倒计时
*/
public void start() {
handler.removeCallbacks(this);
textView.setClickable(false);
handler.post(this);
if (countDownListener != null){
countDownListener.onStart();
}
}
/**
* 结束
*/
private void stop() {
handler.removeCallbacks(this);
textView.setClickable(true);
textView.setText(defaultText);
if (countDownListener != null){
countDownListener.onStop();
}
}
@Override
public void run() {
if (remindSecond > 0) {
textView.setClickable(false);
textView.setText(String.format(countDownText, remindSecond));
remindSecond--;
if (countDownListener != null){
countDownListener.onUpdate(remindSecond);
}
handler.postDelayed(this, 1000);
} else {
stop();
}
}
public void setCountDownListener(OnCountDownListener countDownListener) {
this.countDownListener = countDownListener;
}
/**
* 回调
*/
public interface OnCountDownListener{
void onStart();
void onStop();
void onUpdate(int remindSecond);
}
}
工具使用,只需在程序中调用简简单单的一行代码即可实现倒计时功能,当然也可以添加监听事件
new CountDown(textView, "%s秒", 10).start();
2、DoubleClickExit.java 双击退出程序
public class DoubleClickExitDetector {
public static final String DEFAULT_HINT_MESSAGE = "再按一次退出程序";
public static final int DEFAULT_SPACE_TIME = 2000;
private long spaceTime;
private long lastClickTime;
private String hintMessage;
private Context context;
public DoubleClickExitDetector(Context context) {
this(context,DEFAULT_HINT_MESSAGE,DEFAULT_SPACE_TIME);
}
public DoubleClickExitDetector(Context context, String hintMessage) {
this(context,hintMessage,DEFAULT_SPACE_TIME);
}
public DoubleClickExitDetector( Context context, String hintMessage,long space_time) {
this.context = context;
this.hintMessage = hintMessage;
this.spaceTime = space_time;
}
public boolean onClick(){
long currentTime = System.currentTimeMillis();
boolean result = (currentTime -lastClickTime)< spaceTime;
lastClickTime = currentTime;
if (!result){
Toast.makeText(context, hintMessage, Toast.LENGTH_SHORT).show();
}
return result;
}
public void setSpaceTime(long spaceTime) {
this.spaceTime = spaceTime;
}
public void setHintMessage(String hintMessage) {
this.h``````
tMessage = hintMessage;
}
}
一般在主Activity使用,如下
DoubleClickExitDetector exitDetector = new DoubleClickExitDetector(this);
@Override
public void onBackPressed() {
if (exitDetector.onClick()) {
super.onBackPressed();
}
}
简单的几行代码就搞定了双击退出功能
都是平时的积累,小的改变可以让代码更简洁