首先我们在activity_main.xml里面先定义一个Button空间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
好,现在要我们来看点击事件的四种写法:
1.最常见的一种写法——匿名的内部类做为事件监听器类
package com.basillee.blogdemo; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private Button btnButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnButton=(Button)findViewById(R.id.button1); btnButton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Toast.makeText(MainActivity.this, "button clicked", Toast.LENGTH_LONG).show(); } }); } }
2.内部类做为监听器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
3.Activity直接实现OnClickListener接口
package com.basillee.blogdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private Button btnButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnButton=(Button)findViewById(R.id.button1);
btnButton.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
Toast.makeText(this, "Button clicked!", Toast.LENGTH_LONG).show();
}
}
4.在布局文件中,用android:onClick属性指定对应的方法名实现
activity_main.xml代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
MainActivity.java代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
转自:http://www.cnblogs.com/BasilLee/p/4101284.html