android - 如何在android中创建倒计时onClickListener
问题描述
该场景就像用户触摸视图并保持该视图指定的秒数。类似于长焦点侦听器但具有指定计时器的东西,如果用户在计时器之前将手指移开,那么它将不会调用操作。是否可以?请指导。
解决方案
public class MainActivity extends Activity {
// This example shows an Activity, but you would use the same approach if
// you were subclassing a View.
//Declare timer
CountDownTimer cTimer = null;
@Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
startTimer();
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_UP) :
cancelTimer();
Log.d(DEBUG_TAG,"Action was UP");
return true;
default :
return super.onTouchEvent(event);
}
void startTimer() {
cTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//you can keep updating the ui here.
}
public void onFinish() {
//this is where you want to do something on the basis on long tap action.
}
};
cTimer.start();
}
void cancelTimer() {
if(cTimer!=null)
cTimer.cancel();
}
}
您可以在文档中查看 MotionEvents 。
推荐阅读
- activemq - 无法连接到代理 URL:tcp://localhost:61616。原因:java.net.BindException:地址已在使用:连接
- sql - 如何计算 Big Query 中列的唯一出现次数
- javascript - 当我尝试使用 npm i 安装我的项目包时出现错误
- javascript - 如何在简单的 jQuery 幻灯片中隐藏上一张幻灯片?
- geocoding - here.com 地理编码 REST api 的搜索文本中的哪些字符无效?
- ios - 无法与 WhatsApp 或电子邮件共享 PDF 文件(仅限 IOS)
- swift - Swift 和 CSVImporter:仅导入 .csv 的第一行
- macos - 如何使用 productbuild 在 MacOS Mojave pkg 安装程序中设置背景图像?
- c++ - 由于错误,c++ 代码无法在 Visual Studios 上运行,但未显示错误
- graphdb - 使用 preload 或 loadrdf 工具将数据加载到 graphdb 时如何指定“命名图”?