Reputation: 43
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
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
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
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
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