如何判断哪个按钮被点击的的onClick() [英] How to tell which button was clicked in onClick()
问题描述
我在一个Android应用程序的多个按钮。我想知道,在Java code,哪个按钮被点击。据我所知,这是通过这样一个方法:
I have multiple buttons in an Android app. I want to know, in the Java code, which button was clicked. As far as I can tell, this is accomplished with a single method like this:
public void onClick(View view) {
// Do something
}
和这个方法里面,你必须找出哪一个按钮被点击。这是否正确?
And inside that method, you have to figure out which button was clicked. Is that correct?
如果是这样,我怎么知道哪些被点击?我有()通过findViewById返回的各种按钮的对象。我只是不知道如何使用它们来判断哪些按钮被点击。
If so, how do I tell which was clicked? I do have the various Button objects returned by findViewById(). I just don't know how to use them to tell which button was clicked.
推荐答案
实现视图的OnClickListner在您的活动类。覆盖上点击的方法。
Implement View's OnClickListner in your activity class. Override on click method.
Button b1= (Button) findViewById(R.id.button1);
//find your button id defined in your xml.
b1.setOnClickListener(this);
// You have button OnClickListener implemented in your activity class.
//this refers to your activity context.
我使用了一个敬酒的消息。
I have used a toast message.
<一个href="http://developer.android.com/guide/topics/ui/notifiers/toasts.html">http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Toast.makeText(MainActivity.this,"button1", 1000).show();
//display a toast using activity context ,text and duration
使用开关的情况下可以检查被点击的按钮。
Using switch case you can check which button is clicked.
在你的onClick方法。
In your onClick method.
switch(v.getId()) //get the id of the view clicked. (in this case button)
{
case R.id.button1 : // if its button1
//do something
break;
}
下面是完整的code。
Here's the complete code.
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1= (Button) findViewById(R.id.button1);
Button b2= (Button) findViewById(R.id.button2);
Button b3= (Button) findViewById(R.id.button3);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button1 :
Toast.makeText(MainActivity.this,"button1", 1000).show();
break;
case R.id.button2 :
Toast.makeText(MainActivity.this,"button2", 1000).show();
break;
case R.id.button3 :
Toast.makeText(MainActivity.this,"button3", 1000).show();
break;
}
}
}
这篇关于如何判断哪个按钮被点击的的onClick()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!