连接事件监听器的五种方法是一篇很棒的文章,概述了设置单个事件监听器的各种方法。让我在这里将其扩展为多个侦听器。
1.会员等级
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//attach an instance of HandleClick to the Button
HandleClick handleClick = new HandleClick();
findViewById(R.id.button1).setOnClickListener(handleClick);
findViewById(R.id.button2).setOnClickListener(handleClick);
}
private class HandleClick implements OnClickListener{
public void onClick(View view) {
switch(view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
}
}
2.接口类型
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(handleClick);
findViewById(R.id.button2).setOnClickListener(handleClick);
}
private OnClickListener handleClick = new OnClickListener() {
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
};
}
3.匿名内部阶层
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff
}
});
}
}
4.活动实施
public class main extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
}
5. OnClick事件的视图布局中的属性
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void HandleClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do stuff
break;
case R.id.button2:
// do stuff
break;
}
}
}
并在xml中:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="HandleClick" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="HandleClick" />