问题描述
我不明白为什么我必须实现OnClickListener使用的OnClick法。假设这code:
I don't understand why I have to implement the OnClickListener to use the OnClick-method. Assuming this code:
public class KlickitestActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onClick(View v) {
// code what happens when a click is made
}
从类OnClickListener我只使用方法的onClick(视图v) - 而这一次将被覆盖。为什么我不能只定义没有实现OnClickListener onClick的法?
From the class OnClickListener I only use the method onClick(View v) - and this one is overwritten. Why can't I just define the onClick-method without implementing the OnClickListener?
推荐答案
可以。你可以通过使用一个匿名内部类:
You can. You can do that by using an Anonymous Inner Class :
Button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//Do stuff
}});
Button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//Do stuff
}});
不过实现一个OnClickListener可以更容易地处理事件,并提高了code可读性。即您可以使用一个监听器方法,并传递一个查看
来处理多个按钮/听众提供一个switch语句,类似于:
However implementing an OnClickListener makes it easier to handle events, and improves code readability. i.e You can use one Listener method, and passing a View
to handle multiple buttons/listeners with a switch statement, something similar to :
public void onClick(View view){
switch(view.getId()){
case R.id.Button1:
//Stuff for button 1
break;
case R.id.Button2:
//Stuff for button 2
break;
break;
case R.id.Button3:
//Stuff for button 3
break;
}
这篇关于什么是执行OnClickListener与活动的效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!