第一种:通过匿名类实现对Button事件的监听
首先在XML文件中拖入一个Button按钮,并设好ID,其次在主文件.java中进行控件初始化(Private声明),随后通过SetOnClickListener方法进行内部类的事件监听
详细代码粘贴如下:
package com.example.oncli; import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button; public class MyActivity extends Activity {
private Button btn1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); btn1 = (Button)findViewById(R.id.button1);//此处注意(Button)对View的转化作用; btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("匿名类监听事件设定成功!"); //其余代码自动生成,此处添加控制台输出内容以示区别!;
}
});
}
} 第二种:通过外部类(较麻烦,可直接通过new方法新建)实现Button控件的单击事件监听(主要用于解决多个控件同种用法的代码冗余问题),代码如下:
package com.example.oncli; import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.Toast; public class MyActivity extends Activity {
private Button btn1;
private Button btn2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2); btn1.setOnClickListener(clickl);
btn2.setOnClickListener(clickl);
} View.OnClickListener clickl = new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("123");
}
};
}
第三种:通过实现OnClickListener接口实现事件监听,代码如下:
package com.example.oncli; import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.Toast; public class MyActivity extends Activity implements View.OnClickListener{
private Button btn1;
private Button btn2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2); btn1.setOnClickListener(this);
} public void onClick(View v){
Log.i("tag","外部接口实现事件监听OK");
}
}