0

I want to create a variable number of buttons, and I want them to be adjacent (I cannot use the ListView), so I know I have to inflate a Button somehow. My question is how to inflate the Button, and for each of the created buttons, how to create a listener?

Thanks

Nashwan
  • 63
  • 1
  • 11

1 Answers1

0

I'm a little confused as to what you're asking, but to inflate a button, in your activity, call:

Button myButton = (Button)findViewById(R.id.layout_xml_name);

Then, to add a listener:

myButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
    // Your buttons desired actions
    }
});
ubundude
  • 89
  • 1
  • 1
  • 13
  • Inflating a layout is creating a new "instance" of that layout, well, that's what I know at least. Your code just retrieve the layout of a button, it doesn't inflate the button – Nashwan Apr 25 '13 at 22:52
  • Can you explain what you are trying to do? Are you trying to display different amounts of buttons based on some other input? And if so, is there a maximum number of buttons or unlimited? – ubundude Apr 25 '13 at 22:54
  • well, that's right, I want to create a variable number of buttons and the number is unknown, can be limited. – Nashwan Apr 25 '13 at 22:57
  • My best suggestion would be put each button up to the limit in your layout, adding the attribute: `android:visibility="invisible"`. You can then later programmatically show it again by calling `mButton.setVisibility(VISIBLE)`. In the layout file, the _invisible_ attribute will hide the button, but the space will still be taken up. To utilize the space until it's needed for the button, you can use the _gone_ attribute instead. – ubundude Apr 25 '13 at 23:00
  • I was just doing a little more research on the question and found [this similar question](http://stackoverflow.com/a/7198409/2104186). I think this is more what you're looking for – ubundude Apr 25 '13 at 23:23