-1

I have a problem with the following piece of code:

OnClickListener button_listener = new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                 ImageButton ibutton = (ImageButton) v; 
                 if(player == 0)
                 {

                     ibutton.setClickable(false);
                     ibutton.setImageResource(R.drawable.crossnew);
                     //Toast.makeText(getApplicationContext(),v.getText(), Toast.LENGTH_SHORT).show();
                     player = 1;
                 }

                 else if(player == 1)
                 {
                     ibutton.setClickable(false);
                     ibutton.setImageResource(R.drawable.zeronew);
                     player = 0;
                 }
            }

        };

how to get buttonId was pressed; help me please

Vinra Gunanta Pandia
  • 301
  • 7
  • 10
  • 20
  • 2
    v.getId() in onClick() method. – Hardik Joshi May 01 '13 at 07:24
  • when Toast.makeText(getApplicationContext(),v.getId(), Toast.LENGTH_SHORT).show(); was active, it become false – Vinra Gunanta Pandia May 01 '13 at 07:30
  • Toast.makeText() is overloaded: 1) makeText(Context context, int resId, int duration) 2) makeText(Context context, CharSequence text, int duration) you accidentally used version 1), which takes a resource id as second parameter (and there is no String with the given id) please check my updated answer and for reference http://developer.android.com/reference/android/widget/Toast.html – Suau May 01 '13 at 10:56

4 Answers4

4
OnClickListener button_listener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), Integer.toString(v.getId()), Toast.LENGTH_SHORT)
            .show();
        }
    };
Suau
  • 4,628
  • 22
  • 28
0
if(v.getid() == R.id.testButton){
   Log.e("--->","click on testButton");
}
Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177
0

In your on click use a switch case.

@Override
public void onClick(View v) {
switch(v.getid()) // get id 
{
    case R.id.button1 :
         // button 1 clicked
      break;
    case R.id.button2 :
          // button 2 clicked
      break;   
} 
}

Edit:

In your comment displaying toast you are using application context.

Use a activity context in place of application context. Check the answer by commonsware

When to call activity context OR application context?

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

In Button click function just use

        @Override
        public void onClick(View v) {

                        int id = v.getId();
           }

this will serve your purpose.