添加动态视图-布局重力问题

时间:2019-02-20 13:13:32

标签: android

我正在添加一个看起来像这样的动态布局视图。 Sample View

我将在单击按钮时附加此视图。这是单击按钮时此视图的代码

public void addDynamicView() {
    RelativeLayout relativeLayout = new RelativeLayout(this);
    relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));

    LinearLayout lHori = new LinearLayout(this);
    lHori.setOrientation(LinearLayout.HORIZONTAL);
    //lHori.setWeightSum(3);
    lHori.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

    LinearLayout lVertical = new LinearLayout(this);
    lVertical.setOrientation(LinearLayout.VERTICAL);
    //lVertical.setWeightSum(2);
    lVertical.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));


    Button button = new Button(this);
    button.setLayoutParams(new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)));
    button.setVisibility(View.VISIBLE);
    button.setText("button");

    TextView txtEmpName = new TextView(this);
    txtEmpName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

    txtEmpName.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    txtEmpName.setText("txt1");


    TextView txtEmpDropTime = new TextView(this);
    txtEmpDropTime.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    txtEmpDropTime.setText("txt2");

    lVertical.addView(txtEmpName);

    lVertical.addView(txtEmpDropTime);


    lHori.addView(lVertical);
    lHori.addView(button);

    relativeLayout.addView(lHori);
    linear.addView(relativeLayout);
}

问题是我希望所有按钮都放置在点击按钮下方。 但是我得到这样的输出

如何将所有带有文本按钮的按钮放在点击按钮下面?

3 个答案:

答案 0 :(得分:0)

您可以创建LinearLayout lButton:

LinearLayout lButton = new LinearLayout(this);
lButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

然后将其重力设为重力。

lButton.setGravity(Gravity.END)

并将按钮添加到其中

lButton.addView(button);
lHori.addView(lVertical);
lHori.addView(lButton);

答案 1 :(得分:0)

如果您使用xml这么简单,只需在单击click按钮后创建所需的布局,然后为所有布局设置可见性,然后单击Java on button中的click按钮即可调用可见性视图,以使该布局布局... 希望如此对您有用。

答案 2 :(得分:0)

每个动态视图都是一个水平LinearLayout,其中包含一个垂直LinearLayout和一个按钮。如果您希望按钮右对齐,请使用layout_weigh属性。

您需要做的就是更改代码

来自

lVertical.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

lVertical.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1F));