rakeshmenon
rakeshmenon

Reputation: 43

click events for dynamic array of buttons

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

Upvotes: 2

Views: 2233

Answers (4)

Andrew G
Andrew G

Reputation: 2615

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

Upvotes: 0

Flo
Flo

Reputation: 27445

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

Upvotes: 0

2red13
2red13

Reputation: 11227

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

Upvotes: 2

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

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

Upvotes: 2

Related Questions