Add a Button dynamically to a LinearLayout in Android

21,786

Solution 1

try like this:

linearLayout.addView(
                     btn, 
                     new LayoutParams(
                          LayoutParams.WRAP_CONTENT, 
                          LayoutParams.WRAP_CONTENT)
                     );

Solution 2

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

Share:
21,786
Admin
Author by

Admin

Updated on April 13, 2020

Comments

  • Admin
    Admin about 4 years

    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); 
    
    
        }
    }
    
  • Mike
    Mike almost 11 years
    I would inflate, I dont think adding from code is the best practice