How to create multiple buttons at runtime? + android

后端 未结 3 1922
天涯浪人
天涯浪人 2020-12-19 12:25

I wrote the following code but am not getting how to write OnclickListner() method for all buttons.

public void onCreate(Bundle savedInstanceSta         


        
相关标签:
3条回答
  • 2020-12-19 13:11
    LinearLayout lin = (LinearLayout) findViewById(R.id.linearLayout);
    
    Button b1 = new Button(this);
    
    
    b1.setText("Btn");
    b1.setId(int i=2);
    b1.setonClicklistenor(this);
    lin .addView(b1);
    

    and

    onclick (View v){
    
    
    int i=v.getId();
    
    if (i==2){
    
    ///operation
    }
    }
    }
    
    0 讨论(0)
  • 2020-12-19 13:22

    If you want the buttons to do different things, you could have your Activity extend OnClickListener, set b.setOnClickListener(this) in the loop, and add something like

    @Override
    public onClick(View v)
    {
      // get who called by
      String sTag = (String) v.getTag();
    
      if (sTag.equals("button1"))
      {
        //do some stuff  
      }
      else if (sTag.equals("button2"))
      {
        //do some other stuff
      }
      // and so on
    }
    

    to handle the clicks.


    And I'm editing this in here because the lack of line breaks makes comments ambiguous:

    int iBtnID = v.getId(); 
    switch (iBtnID) 
    {
      case 101: 
        // do stuff; 
        break; 
      case 102: 
        // do other stuff 
        break; 
      // and so on 
    }
    
    0 讨论(0)
  • 2020-12-19 13:23

    You can use an anonymous inner method like this:

    Button b = new Button(this);
    b.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
        }
    });
    b.setText("" + i);
    b.setTag("button" + i);
    b.setWidth(30);
    b.setHeight(20);
    
    0 讨论(0)
提交回复
热议问题