安卓按钮点击事件、触摸事件、长按事件的实现与根本

<?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"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/btn"
        android:backgroundTint="@color/btn_colro"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮"
    />
</LinearLayout>
package com.example.btn;

import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //实例化btn按钮
        Button  btn = findViewById(R.id.btn);
        //点击事件 onclick
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("点击","123123");
//                Intent intent = new Intent(MainActivity.this,MainActivity.class);
//                startActivity(intent);
            }
        });
        //长按事件 setOnLongClickListener
         btn.setOnLongClickListener(new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
              Log.d("点击","7893");
              return false;
          }
      });
         //触摸事件setOnTouchlistener
         btn.setOnTouchListener(new View.OnTouchListener() {
             @Override
             public boolean onTouch(View v, MotionEvent event) {
                 Log.e("触摸",""+ event.getAction());
                 return false;
             }
         });
    }
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐