开发者

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 But开发者_StackOverflow中文版ton[c.getCount()];
 for( i=0;i<c.getCount();i++)
 {
    addAsFriend[i] = new Button(this);
 }


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


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜