我在16 按钮
S(数字,加,减等)在我的布局XML文件中。
I have in 16 Button
s (numbers, plus, minus etc) in my layout XML file.
我不知道如何检查哪个按钮是pressed。
I'm wondering how to check which button was pressed.
我的想法是,我会为每个按钮使用的onClick()
的方法,但这种方法是有点不切实际,因为我有这16个的onClick()
每个按钮的方法之一。
My idea is, that I will for each button use onClick()
method but this method is a bit impractically, because I will have 16 of these onClick()
methods one for each Button.
有没有更好的方法?
您可以与他们所有的处理在实现OnClickListener,或活动类中,如果你喜欢一个类...
You can deal with them all in a single class that implements OnClickListener, or within the activity class if you like...
import android.view.View.OnClickListener;
public class MyActivity extends Activity implements OnClickListener {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonA = (Button) findViewById(R.id.buttonA);
buttonA.setOnClickListener(this);
Button buttonB = (Button) findViewById(R.id.buttonB);
buttonB.setOnClickListener(this);
}
//etc... etc...
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonA:
// do something
break;
case R.id.buttonB:
// do something else
break;
}
}
}