如何在 Android 中使用动作移动事件?
此示例演示如何在 Android 中使用动作移动事件。
步骤 1 − 在 Android Studio 中创建新项目,依次转到文件 ⇒ 新项目,填写所有必需的详细信息以创建一个新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <TextView android:id="@+id/actionEvent" android:textSize="40sp" android:layout_marginTop="30dp" android:layout_width="wrap_content" android:layout_height="match_parent" /> </LinearLayout>
在上文中,我们已经采用了一个文本视图来执行动作移动事件。
步骤 3 − 将以下代码添加到 src/MainActivity.java
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView textView;
@SuppressLint({"RestrictedApi", "ClickableViewAccessibility"})
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView actionEvent = findViewById(R.id.actionEvent);
actionEvent.setText("Action Move");
actionEvent.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Toast.makeText(MainActivity.this,"moving: (" + x + "," + y +")",Toast.LENGTH_LONG).show();
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
});
}
}尝试运行应用程序。我假设你已经将实际的 Android 手机设备与自己的电脑连接好。从 Android Studio 运行应用,打开一个项目活动文件,然后从工具栏中点击运行
图标。选择你的移动设备作为选项,然后查看你的移动设备,它会显示你的默认屏幕 –

点击此处 下载项目代码
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP