0

I have 1 function to print the text of the button, and i use that function for the 3 button, how do i know in what button the user click? (sorry but my english is low) Example:

        public void function(View view) {
        TextView text = (TextView) findViewById(R.id.textView);
        Button button1= (Button) findViewById(R.id.button3);
        Button button1= (Button) findViewById(R.id.button4);
        Button button1= (Button) findViewById(R.id.button5);

        text.setText(button <?> .getText()); }

is the number of the button the user click

Its any way to know in which button the user click? Please help, Thanks.

  • possible duplicate of [Android OnClickListener - identify a button](http://stackoverflow.com/questions/3320115/android-onclicklistener-identify-a-button) – Zeus Jul 21 '14 at 21:19

3 Answers3

0

The view that is passed in is the one that was clicked, therefore it has the id.

view.getId() == R.id.button3

If you still need help, share more of your code.

Erik B
  • 2,810
  • 1
  • 34
  • 38
0

Well you will require some onclick listeners for the button, you can then set an id or name in the onclick e.g

 final Button button1 = (Button) findViewById(R.id.button_id);
     button1.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             text.settext("Button1 Clicked")
         }
     });
dave
  • 1,410
  • 1
  • 16
  • 42
0

you can define one click listener and set this listener for all buttons. For example:

private OnClickListener genericListerner = new OnClickListener() { 
    public void Click(View v) {
        switch(v.getId())
        {
              case R.id.button3:
               text.setText(button3.getText().toString());
              break;
              case R.id.button4:
              text.setText(button4.getText().toString());
              break;
              case R.id.button5:
              text.setText(button5.getText().toString());
              break;
              default:
              //do something
    } 
}; 

and you set the listeners like the following:

button3.setOnClickListener(genericListener);
button4.setOnClickListener(genericListener);
button5.setOnClickListener(genericListener);

I am not sure whether this is what you are asking, but what this code basically does is that, if you click button 3 it sets the textview's text to button 3's text, if you click button 4 it sets the textview's text to button 4's text and if you click button 5, it sets the textview's text to button 5's text.

Hope this helps.

yrazlik
  • 10,411
  • 33
  • 99
  • 165