android-layoutandroid-layoutparams

Setting LayoutParams but its not working android


Trying to create a linear layout programmatically and setting its width and height by layout params. But it seems layout params isn't working.

this is the code:

 // CREATING A NEW LINEAR LAYOUT PROGRAMMATICALLY
    LinearLayout linearLayout = new LinearLayout(getActivity());
    ViewGroup.LayoutParams layoutParams = new 
 ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 
 ViewGroup.LayoutParams.WRAP_CONTENT);
    linearLayout.setLayoutParams(layoutParams);
    linearLayout.setOrientation(LinearLayout.HORIZONTAL);

    // CREATING CHILDDRENS (TEXT VIEWS)
    TextView name = new TextView(getContext(), null, 0, R.style.item_layout_style);
    name.setText("Pine");
    TextView qty = new TextView(getContext(), null, 0, R.style.item_layout_style);
    qty.setText("10");
    TextView cost = new TextView(getContext(), null, 0, R.style.item_layout_style);
    cost.setText("785");
    TextView tCost = new TextView(getContext(), null, 0, R.style.item_layout_style);
    tCost.setText("1000");



    // SET TEXT VIEW TO LINEAR LAYOUT
    linearLayout.addView(name);
    linearLayout.addView(qty);
    linearLayout.addView(cost);
    linearLayout.addView(tCost);

    // SET LINEAR LAYOUT TO PINE LAYOUT
    LinearLayout daddy= (LinearLayout) view.findViewById(R.id.layout);
    daddy.addView(linearLayout, 2);

    // Return the view
    return view;

I have root layout (daddy) which has many linear layouts (vertically oriented), but I need to create a linear layout programmatically and add that to "daddy". But the text views are sticked together, they aren't getting the entire space horizontally.

Do help me!


Solution

  • Everything is fine with the code. It is the style that I tried to give to text views, they weren't getting layout weight, width and height. How did I find this out? Well I set the linear layout's background-color to black to see if it's really not getting width and height set by LayoutParams. And I wasn't wrong! Width was set to match parent. So what I did was create a new layout param for text views and set it to them.