
package com.example.myapplication5;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;public class TouchActivity extends AppCompatActivity {private TextView content;// 在 Activity 类中添加private GestureDetector gestureDetector;String[] news={"第一页","第二页","第三页","第四页","第五页"};int index=0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_touch);content = findViewById(R.id.content);content.setText(news[0]);// 初始化手势检测器gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {@Overridepublic boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {if(e1.getX() >= e2.getX() ) {if(index<=news.length-2){index++;content.setText(news[index]);}}else{//右滑减小indexif(index>=1){index--;content.setText(news[index]);}}return true;}});}// 重写 onTouchEvent 方法@Overridepublic boolean onTouchEvent(MotionEvent event) {gestureDetector.onTouchEvent(event);return super.onTouchEvent(event);}
}
<?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:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:id="@+id/content"android:layout_width="match_parent"android:layout_height="match_parent"android:text="左滑查看下一页\n右滑查看上一页"/></LinearLayout>