Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

android - How to tell which button was clicked in onClick()

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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;
}

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;  


    }

}
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...