设置LayoutParams,但无法使用Android



尝试以编程方式创建线性布局,并通过布局参数设置其宽度和高度。但似乎布局参数不起作用。

这是代码:

 // 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;

我的root布局(daddy)具有许多线性布局(垂直方向),但是我需要以编程方式创建线性布局,并将其添加到" daddy"中。但是文本视图粘在一起,它们并没有水平获取整个空间。

确实可以帮助我!

代码一切都很好。这是我试图给文本视图的样式,它们没有得到布局的重量,宽度和高度。我怎么找到这个?好吧,我将线性布局的背景色设置为黑色,以查看它是否真的没有得到LayoutParams设置的宽度和高度。而且我没错!宽度设置为匹配父母。因此,我所做的是为文本视图创建一个新的布局参数并将其设置为它们。

最新更新