-1

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

这是代码:

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

我有根布局(爸爸),它有许多线性布局(垂直方向),但我需要以编程方式创建一个线性布局并将其添加到“爸爸”。但是文本视图是粘在一起的,它们并没有水平放置整个空间。

帮帮我吧!

4

1 回答 1

0

代码一切正常。这是我试图赋予文本视图的样式,它们没有获得布局重量、宽度和高度。我是怎么发现的?好吧,我将线性布局的背景颜色设置为黑色,看看它是否真的没有得到 LayoutParams 设置的宽度和高度。而且我没有错!宽度设置为匹配父级。所以我所做的是为文本视图创建一个新的布局参数并将其设置为它们。

于 2017-12-06T10:37:29.033 回答