Silence_burst 2017-04-18 13:48 采纳率: 0%
浏览 3116
已结题

显示持续触摸时长,MotionEvent 触摸事件处理

用MotionEvent写了一个显示触摸时间的程序,用event.getEventTime() - event.getDownTime();来计算按下的时间长短,但是计算出来的时间不准确,作为一个新手,希望各位大神帮忙瞅瞅这个问题出在哪里了,怎样才能正确计算出触摸时长。

代码如下:


public class MainActivity extends Activity {
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = (TextView) findViewById(R.id.text);
        final ImageView iv = (ImageView) findViewById(R.id.action);

        OnTouchListener otl = new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                long time = event.getEventTime() - event.getDownTime();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    text.setText(R.id.text + time + "ms");
                }
                return true;
            }
        };
        iv.setOnTouchListener(otl);
    }
}

XML代码如下:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context="com.example.chumo.MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="触摸持续时间为:"
        android:textSize="25dp"
        android:id="@+id/text"/>

    <ImageView
        android:id="@+id/action"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/src"
        android:scaleType="fitXY"/>
</LinearLayout>

运行的结果如下图:

图片说明

按下屏幕大约1s之后:

图片说明

  • 写回答

1条回答 默认 最新

  • qq_37153767 2017-04-19 14:55
    关注

    public boolean onTouch(View v, MotionEvent event) {
    long startTime=event.getDownTime();
    long endTime=event.getEventTime();
    long touchTime =endTime -startTime ;
    if (MotionEvent.ACTION_UP == event.getAction()) {
    txt.setText("触摸持续时间为:" + touchTime + "毫秒");
    }
    return true;
    }

    评论

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果