4

I am working on a project that needs to add buttons dynamically. But whenever I run my application the application force closes. I've learned that the problem is when I try to add buttons.

package com.Feras.TestProject;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class TestProject extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    AddAll();
    // Set Text for the button in the Old Testament



}
public void AddAll() {
    LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout1);
    Button btn = new Button(this); 
    btn.setText("MyButton"); 
    linearLayout.addView(btn); 


    }
}
1
  • 1
    Please use 'adb logcat' to get a proper stacktrace of the application (it resides in the platform-tools folder in installed Android SDk). Commented Apr 12, 2011 at 7:50

3 Answers 3

2

try like this:

linearLayout.addView(
                     btn, 
                     new LayoutParams(
                          LayoutParams.WRAP_CONTENT, 
                          LayoutParams.WRAP_CONTENT)
                     );
Sign up to request clarification or add additional context in comments.

1 Comment

I would inflate, I dont think adding from code is the best practice
1

there will only occure an error if linearLayout is null, ensure that layout1 is a valid Item of R.layout.main

Comments

0

Try the following in your custom activity class:

this.addContentView(call,
    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.