Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách sử dụng sự kiện Action Up (nhấc lên) trong Android

Giới thiệu

Ví dụ này minh họa cách xử lý sự kiện ACTION_UP (ngón tay nhấc lên khỏi màn hình) trên một View.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://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>

Bước 3: Viết logic (src/MainActivity.java)

package com.example.myapplication;

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.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @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 UP");

        actionEvent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = MotionEventCompat.getActionMasked(event);
                if (action == MotionEvent.ACTION_UP) {
                    Toast.makeText(MainActivity.this, "Đã nhấc ngón tay khỏi TextView", Toast.LENGTH_LONG).show();
                    return true;
                }
                return false;
            }
        });
    }
}

ACTION_UP xảy ra khi ngón tay rời khỏi màn hình. Thường dùng để xác nhận một lần nhấn hoàn chỉnh (click).

Chạy ứng dụng

Chạy trên thiết bị thật. Chạm và nhấc ngón tay khỏi TextView sẽ hiển thị Toast.

Cách sử dụng sự kiện Action Up (nhấc lên) trong Android