Android onClick事件三种实现方法
16lz
2021-01-23
import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class HelloActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btnMethod01; Button btnMethod02; Button btnMethod03; btnMethod01 = (Button)findViewById(R.id.button1); btnMethod02 = (Button)findViewById(R.id.button2); btnMethod03 = (Button)findViewById(R.id.button3); //第一种方法:匿名类 btnMethod01.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ Toast.makeText(HelloActivity.this,R.string.method01 ,Toast.LENGTH_SHORT).show(); } }); //添加监听事件 btnMethod02.setOnClickListener(new button1OnClickListener()); } //第二种方法:内部类实现 有两部 1.写内部类 2.添加监听事件 private class button1OnClickListener implements OnClickListener{ public void onClick(View v){ Toast.makeText(HelloActivity.this,R.string.method02, Toast.LENGTH_SHORT).show(); } } //第三种方法:用xml方法配置,该名称要与 main.xml 中button03的 //android:onClick="OnClickButton03"的名字一样 public void OnClickButton03(View v){ Toast.makeText(HelloActivity.this,R.string.method03 ,Toast.LENGTH_SHORT).show(); } }
<?xml version="1.0" encoding="utf-8"?>
更多相关文章
- android学习——android 常见的错误 和 解决方法
- Android中Preference的使用以及监听事件分析
- Android详细的对话框AlertDialog.Builder使用方法
- Android的四种点击事件
- Android Studio 3.0 gradle提示太老 解决方法
- Android 中自定义控件和属性(attr.xml,declare-styleable,TypedA
- Android笔记Android基于事件监听器处理机制
- [Android]LayoutInflater的inflate方法半详解
- Android与Unity交互调用mUnityPlayer.quit()方法退出返回上一个A