user1793791
user1793791

Reputation: 21

Creating button dynamically

hey guys need a little help........my intention is to develop an app which contains just a button... and on clicking it it must create another button on the screen dynamically.......

here's my code...

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Button bee=new Button(getBaseContext());
            bee.setText("hello:");
             RelativeLayout a;
            a=(RelativeLayout)findViewById(R.layout.activity_main);
    a.addView(bee,new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        }
    });

this code is error free but when executed says "unfortunately 'myapplication' has stopped"....

pls do help guys..( my sole aim is to create widgets dynamically ,hence tried dis program). if u have any other suggestions pls post nd comment

Upvotes: 1

Views: 205

Answers (5)

yugidroid
yugidroid

Reputation: 6690

You are trying to "find" a layout which can't exist! Please, make sure you have defined a RealtiveLayout with a valid id and then do

a=(RelativeLayout)findViewById(R.id.valid_layout_id);

instead of

a=(RelativeLayout)findViewById(R.layout.activity_main);

Upvotes: 0

J.D.
J.D.

Reputation: 1411

You are finding id rather then layout

so change this line:

a=(RelativeLayout)findViewById(R.id.activity_main); 

Upvotes: 0

Ravi
Ravi

Reputation: 2367

try with this code i think you are getting problem just because of not setting the parameters properly so check with this code-

 LinearLayout container = (LinearLayout)findViewById(R.id.container);

    Button btn = new Button(this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.MATCH_PARENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT);
    btn.setLayoutParams(lp);

    container.addView(btn);

Upvotes: 0

Akshay
Akshay

Reputation: 2534

Try this.

RelativeLayout rLayout = (RelativeLayout )findViewById(R.id.relativeLayout); // Here this should be id of your relative layout.
Button btn = new Button(this);
rLayout.addView(btn);

Upvotes: 0

Waza_Be
Waza_Be

Reputation: 39564

 a=(RelativeLayout)findViewById(R.layout.activity_main);

activity_main is a layout, not a RelativeLayout widget!

you should use

 a=(RelativeLayout)findViewById(R.id.my_relative_layout);

Please post the stack trace (logcat) so you will get better and faster answer.

Upvotes: 1

Related Questions