Androidのタッチスクリーンイベントを処理する方法

Androidでは、タッチスクリーンイベントを設定するための手順は次のとおりです。

  1. TouchView などのビューを継承するカスタムビュークラスを作成します。
public class TouchView extends View {
    // 构造方法
    public TouchView(Context context) {
        super(context);
    }

    // 重写onTouchEvent方法来处理触摸事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 在这里处理触摸事件
        return super.onTouchEvent(event);
    }
}
  1. カスタムビューをアクティビティのレイアウトファイルに追加します。
<com.example.myapp.TouchView
    android:id="@+id/touchView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  1. アクティビティ内でそのカスタムビューを見つけてタッチリスナーを設定します。
public class MainActivity extends AppCompatActivity {
    private TouchView touchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 找到自定义视图
        touchView = findViewById(R.id.touchView);

        // 设置触摸监听器
        touchView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 在这里处理触摸事件
                return true;
            }
        });
    }
}

タッチリスナーのonTouchメソッドでは、eventパラメータからタッチイベントの種類を判定して、座標の取得やジェスチャーの判定などの対応処理を行うことができます。

bannerAds