Button控件监听器的三种实现方法

时间:2022-12-16 22:39:37

Button按钮控件监听器的三种实现方法:

1、匿名内部类实现

2、外部类监听实现

3、接口方式实现


首先在布局文件中添加三个按钮,每个button对应实现一种实现方法

<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"
tools:context="com.example.click.MainActivity"
android:orientation="vertical">

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="内部类" />

<Button
android:id="@+id/button_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="外部类" />

<Button
android:id="@+id/button_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="接口" />

</LinearLayout>


第一种:内部类实现监听

button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", 2000).show();
}
});


第二种:外部类实现监听

 button_2 = (Button)findViewById(R.id.button_2);
button_2.setOnClickListener(new MyClick(){
@Override
public void onClick(View v) {
super.onClick(v);
Toast.makeText(getApplicationContext(), "click2", 2000).show();
}
});
//并实现外部类
class MyClick implements OnClickListener{@Overridepublic void onClick(View v) {
//所有重写该方法的,且调用super.onClick(v);,都会执行的逻辑v.setAlpha(0.5f);}}


第三种:接口方式实现监听

button_3 = (Button)findViewById(R.id.button_3);
button_3.setOnClickListener(this);
//并重写onClick方法
@Override
public void onClick(View v) {Toast.makeText(getApplicationContext(), "click3", 2000).show();}


贴上全部的代码

package com.example.click;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener{

private Button button,button_2,button_3;

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

button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", 2000).show();
}
});
button_2 = (Button)findViewById(R.id.button_2);
button_2.setOnClickListener(new MyClick(){
@Override
public void onClick(View v) {
super.onClick(v);
Toast.makeText(getApplicationContext(), "click2", 2000).show();
}
});
button_3 = (Button)findViewById(R.id.button_3);
button_3.setOnClickListener(this);

}

@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click3", 2000).show();
}

}

class MyClick implements OnClickListener{

@Override
public void onClick(View v) {

v.setAlpha(0.5f);
}

}