Five Ways to Wire Up an Event Listener是一篇很棒的文章,概述了各种设置单个事件监听器的方式。我在这里将其扩展到多个听众。
1. 成员类
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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:
break;
case R.id.button2:
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:
break;
case R.id.button2:
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) {
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
}
});
}
}
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:
break;
case R.id.button2:
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:
break;
case R.id.button2:
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" />