实验内容
一、实验要求和目的
- 掌握基于监听的事件处理机制,根据需求能够编写相应的事件处理程序。
- 能够熟练应用各种布局管理器和控件进行界面设计。
二、实验环境 - 部署有Android Studio和Android SDK的主机;
- 建议在机房的HelloWorld例子上完成。
三、上机操作参考步骤
1、设计一个显示用户触摸持续时间的小程序,在layout文件夹的布局文件activity_main.xml中设计如下界面(2个TextView、1个EditText和1个ImageView),触摸ImageView,在TextView中显示触摸时间。
2、参考资料:
(1)以下是drawable文件,需复制到drawable文件夹。
background.jpg:ImageView加载显示的图片
(2)代码:
查看android.view.MotionEvent类,了解MotionEvent类的相关常量和函数。
public final long getDownTime()
public final long getEventTime()
public final int getAction()
public static final int ACTION_UP = 1;
public static final int ACTION_DOWN = 0;
下面是MotionEvent类的简介(https://www.cnblogs.com/baiqiantao/p/5631010.html)
实验代码
- 布局文件XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="触摸持续时间"/>
<EditText
android:id="@+id/et"
android:layout_width="200sp"
android:layout_height="wrap_content"
android:textColor="@color/colorAccent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="毫秒"/>
</LinearLayout>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/background"/>
</LinearLayout>
- 逻辑处理Java
package org.crazyit.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
/**
* Description:<br>
* 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br>
* Copyright (C), 2001-2020, Yeeku.H.Lee<br>
* This program is protected by copyright laws.<br>
* Program Name:<br>
* Date:<br>
* @author Yeeku.H.Lee kongyeeku@163.com<br>
* @version 1.0
*/
public class MainActivity extends Activity implements OnTouchListener
{
private ImageView iv;
private EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//加载布局
setContentView(R.layout.activity_main);
iv=findViewById(R.id.iv);
et=findViewById(R.id.et);
iv.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v,MotionEvent event){
// TODO Auto-generated method stub
long time=event.getEventTime()-event.getDownTime();//计算触摸持续时间
String s = String.valueOf(time);
if(event.getActionMasked()==MotionEvent.ACTION_UP){
et.setText(s);
}
return true;
}
}
实验结果展示
相关知识点:
触摸事件 Touch MotionEvent ACTION
相应的函数以及常量:例如
• ACTION_DOWN: 表示用户开始触摸(在第一个点被按下时触发)
• ACTION_MOVE: 当有点在屏幕上移动时触发,注意的是,由于灵敏度很高,所以基本上只要有点在屏幕上,此事件就会不停地被触发
• ACTION_UP:表示用户抬起了手指(当屏幕上唯一的点被放开时触发)
• getDownTime() //按下开始时间
• getEventTime() // 事件结束时间
对于触摸事件的详情参见改博主的博客触摸事件