用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之后: