2

with the below code i can generate an array of button.but i cant specify the click events for these button.how can i do these

Button addAsFriend[] = new Button[c.getCount()];
 for( i=0;i<c.getCount();i++)
 {
    addAsFriend[i] = new Button(this);
 }
0

4 Answers 4

2
Button addAsFriend[] = new Button[c.getCount()];
 for( i=0;i<c.getCount();i++)
 {
    Button btn = new Button(this);
    btn.setOnClickListener(new View.OnClickListener() {

       @Override
       public void onClick(View v) {
        // your code here
       }
     };);
    addAsFriend[i] = btn;
 }
Sign up to request clarification or add additional context in comments.

Comments

2
Button addAsFriend[] = new Button[c.getCount()];
for( i=0;i<c.getCount();i++)
{
 addAsFriend[i] = new Button(this);
 ((Button)addAsFriend[i]).setOnClickListener(myclickListener);
}

Comments

0

You can implement the OnClickListener Interface in you activity. Doing this you will have to override the onClick() method. Then you can pass the activity as an OnClickListener to each button.

public class YourActivity implements OnClickListener {

     public void onCreate(){
         ...

         Button addAsFriend[] = new Button[c.getCount()];
         for( i=0;i<c.getCount();i++)
         {
             addAsFriend[i] = new Button(this);
             ((Button)addAsFriend[i]).setOnClickListener(this);
         }    
        ...
    }

    public void onClick(View v){
        // Put your listener code here.
    }
}

Comments

0

...And if you want to retrieve the index of that button then use a map!

Map<View,Integer> buttonMap = new HashMap<View,Integer>();

Button addAsFriend[] = new Button[c.getCount()];

for( i=0;i<c.getCount();i++)
{
   Button btn = new Button(this);
   buttonMap.put(btn,i);

   btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         int index = buttonMap.get( v );

         // do something with index here

      }
   };);
   addAsFriend[i] = btn;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.