Android Button四种点击事件和长按事件

项目XML代码

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="doClick"
android:text="xml添加doClock"/> <Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="匿名内部类点击"/> <Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="自定义点击事件"/> <Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="继承方式"/> <Button
android:id="@+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="长按点击事件"/> </LinearLayout>

JAVA代码:

 package com.example.a11658.buttondemo;

 import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button2, button3, button4, button5; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); initView();
} private void initView() {
button2 = findViewById(R.id.button2);
button3 = findViewById(R.id.button3);
button4 = findViewById(R.id.button4);
button5 = findViewById(R.id.button5); button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//匿名内部类实现点击事件
Toast.makeText(MainActivity.this, "匿名内部类的点击事件", Toast.LENGTH_SHORT).show();
}
}); button3.setOnClickListener(new MyListener());
button4.setOnClickListener(this);
button5.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast.makeText(MainActivity.this, "长按事件", Toast.LENGTH_SHORT).show();
return false;
}
});
} public void doClick(View view) {
//xml通过onClick实现点击事件
Toast.makeText(this, "xml点击实现", Toast.LENGTH_SHORT).show();
} @Override
public void onClick(View v) {
//继承方式
Toast.makeText(this, "继承点击", Toast.LENGTH_SHORT).show();
} class MyListener implements View.OnClickListener { @Override
public void onClick(View v) {
//自定义方式
Toast.makeText(MainActivity.this, "自定义点击事件", Toast.LENGTH_SHORT).show();
}
}
}
备注:Button数量不多的情况下推荐使用第二种,匿名内部类的方式实现;反之则推荐使用第四种,Activity继承View.OnClickListener实现

代码链接:https://github.com/1165863642/ButtonDemo
上一篇:LinkedHashMap和HashMap区别


下一篇:Vue中结合clipboard实现复制功能