使TextView显示在另一个TextView上方

时间:2017-08-02 21:39:43

标签: android layout textview

您好我正在尝试通过代码使2个TextViews彼此之上。 我的问题是: 我怎么能把它们叠在一起呢?

示例代码

private TextView DurrationView;
private TextView DurrationViewoverall;

DurrationView = new TextView(getContext());
    DurrationView.setText("");
    addView(DurrationView);


    DurrationViewoverall = new TextView(getContext());
    DurrationViewoverall.setPadding(5,5,5,5);
    DurrationViewoverall.setText("");
    addView(DurrationViewoverall);

我试图将DurrationView显示在DurrationViewoverall上方。 他们所在的课程扩展了线性布局。

2 个答案:

答案 0 :(得分:2)

将LayoutParams添加到textview并使线性布局成为垂直方向

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

DurrationView = new TextView(getContext());
LinearLayout.LayoutParams durrationViewParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
DurrationView.setLayoutParams(durrationViewParams);
DurrationView.setText("Text1");
linearLayout.addView(DurrationView);


DurrationViewoverall = new TextView(getContext());
LinearLayout.LayoutParams durrationViewoverallParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
DurrationViewoverall.setLayoutParams(durrationViewoverallParams);
DurrationViewoverall.setPadding(5,5,5,5);
DurrationViewoverall.setText("Text2");
linearLayout.addView(DurrationViewoverall);

addView(linearLayout);

答案 1 :(得分:0)

检查LinearLayout是否设置为垂直方向。如果设置正确,您可能还需要以编程方式设置TextView的LayoutParams。