0

I'm having a problem adding function to the buttons I created dynamically

What I'm trying to do is I have a house I can set different types of room like BEDROOM, KITCHEN, GARAGE etc represented as BUTTONS and then each room has different types of appliances and others stuff which I can also set and also represent by BUTTONS. The problem is, some users have different number of ROOMS, some have 2 BEDROOMS or 3 so I have to make the BUTTONS for the rooms dynamic and add different function to each BUTTON. How can I implement this?

for example:

Button room = new Button(this);
room.setText("Bedroom");
room.setID(1);
/* set function for this button like change the textView or add numbers */

and then when I click the button again to add bedroom it will create a new BEDROOM but with a different function. Is that possible?

philip
  • 1,292
  • 3
  • 24
  • 44
  • http://stackoverflow.com/questions/8079799/how-do-i-create-a-button-programatically?rq=1 –  Sep 13 '12 at 08:45
  • I'm sorry my question lack more explanation, I already know how to do that sir, just a sec I'll edit my question – philip Sep 13 '12 at 08:49
  • @philip, can you explain more about your problem. The short answer to your question (if i understand it correctly) is to set the onClickListener property to implement different functionality for different buttons. – Gan Sep 13 '12 at 09:44

1 Answers1

0

You'll need to set the button property "clickable", which is false by default when you create a button programatically, to true and set the onClickListener for each button.

Button room = new Button(this);
room.setText("Bedroom"); 
room.setID(1); 
room.setClickable(true);
room.setOnClickListener(new OnClickListener(){
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            // Here is where you'd put in the specific functionality for this button
        }
    });
zabawaba99
  • 507
  • 1
  • 6
  • 13
  • but how can i make that button not disappear after I close the app? – philip Sep 14 '12 at 02:11
  • Well, since you created it dynamically, you would have to save the state of the button when the app is closed using the shared preferences or SQLite Database. I'd recommend using the shared preferences since it's more lightweight for this situation. What you could do is store a boolean in the preferences which would decide if that button has been placed or not. You would check this boolean in your onCreate method. If it has been created then you place and set the button using the code above. You can find more storage options here http://developer.android.com/guide/topics/data/data-storage.html – zabawaba99 Sep 14 '12 at 15:23