Zapnologica
Zapnologica

Reputation: 22576

Defining a Linear Layout progmatically

I am trying to dynamically create a linear layout with a dynamic number of buttons based on certain parameters. So far I have some code that compiles but when it runs it does not display anything.

public void displayMenu() 
{
    LinearLayout lin =  new LinearLayout(CategoryMenu.this);        
    lin.setOrientation(LinearLayout.VERTICAL);
    lin.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    ArrayList<Button> btnList= new ArrayList<Button>();

    //Test Button
    Button btn1= new Button(this);
    btn1.setText("Dylan");      
    lin.addView(btn1);  

    for (int i =0 ; i < 5; i++){

    btnList.add(new Button(this));
    btnList.get(i).setText("Hello:"+i);     
    lin.addView(btnList.get(i));
    Log.i("CategoryMenu","Adding btn to view");
    }       
}

What am i doing incorrectly? I'm sure that i'm missing some thing silly here.

Upvotes: 1

Views: 79

Answers (5)

navneet raval
navneet raval

Reputation: 1

LinearLayout lin = new LinearLayout(CategoryMenu.this);
lin.setOrientation(LinearLayout.VERTICAL); lin.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

ArrayList<Button> btnList= new ArrayList<Button>();

Upvotes: 0

ShineDown
ShineDown

Reputation: 1879

You have to add lin too the layout. At present you have just created a Linearlayout, but you have not attached it to any layout.

Upvotes: 0

Nargis
Nargis

Reputation: 4787

Before lin.addView(btn1);

You should define layoutparams for Button like:

 // Defining the layout parameters of the Button
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);

        // Setting the parameters on the Button
        tv.setLayoutParams(lp);

Upvotes: 0

It seems that you're not adding that linear layout to a viewgroup parent.

After all your code you should add something like

myParentViewGroup.add(lin);

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157487

you have to add lin to the current hierarchy of view, or creating a new one calling setContentView(lin);

Upvotes: 2

Related Questions