5

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

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LinearLayout layout = (LinearLayout) findViewById(R.id.ll1Relative);
    for (int i = 1; i < 10; i++) {
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        );
        Button b = new Button(this);
        b.setText(""+ i);
        b.setId(100+i);
        b.setWidth(30);
        b.setHeight(20);
        layout.addView(b, p);
    }
}
stealthjong
  • 10,858
  • 13
  • 45
  • 84
Pramod
  • 51
  • 1
  • 4

3 Answers3

2

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);
stealthjong
  • 10,858
  • 13
  • 45
  • 84
RoflcoptrException
  • 51,941
  • 35
  • 152
  • 200
  • The thing is i want to write SQLite query for each of the buttons separately.Is it better to use swith case? There are 10 buttons and each has separate query. – Pramod Apr 23 '11 at 09:35
0

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 
}
Ben Williams
  • 6,027
  • 2
  • 30
  • 54
-1
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
}
}
}
  • 1
    I don't see how this answers the question. The problem the OP had was how to handle the click events for the buttons. – Michael Jul 21 '14 at 10:29