如何在 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 執行應用,開啟一個專案活動檔案,然後從工具欄中點選執行 圖示。選擇你的移動裝置作為選項,然後檢視你的移動裝置,它會顯示你的預設螢幕 –

點選此處 下載專案程式碼

更新於: 2019 年 7 月 30 日

382 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.