为什么这些TextView不是彼此相邻的?

时间:2014-12-17 12:15:50

标签: android layout textview

我需要彼此相邻地动态创建多个TextView。当我运行下面的代码时,结果不是我的预期。 t1和t2与另一个相距很远

RelativeLayout journals = (RelativeLayout) findViewById(R.id.main);

    layoutUserDoes = new LinearLayout(this);

    layoutUserDoes.setLayoutParams(new LayoutParams(journals.getWidth() , 100));
    layoutUserDoes.setY(0);
    layoutUserDoes.setBackgroundColor(Color.WHITE);
    journals.addView(layoutUserDoes);

    TextView t1=new TextView(this);
    t1.setTextSize(20);
    t1.setText("t1");
    t1.setBackgroundColor(Color.GRAY);
    t1.setTextColor(Color.BLACK);
    t1.setWidth(50);
    t1.setHeight(40);
    t1.setX(20);

    layoutUserDoes.addView(t1);

    TextView t2=new TextView(this);
    t2.setTextSize(20);
    t2.setText("t2");
    t2.setBackgroundColor(Color.GRAY);
    t2.setTextColor(Color.BLACK);
    t2.setWidth(50);
    t2.setHeight(40);
    t2.setX(70);

    layoutUserDoes.addView(t2);

enter image description here

4 个答案:

答案 0 :(得分:1)

因为您正在使用:

t2.setX(70);

答案 1 :(得分:1)

您将这两个View放入LinearLayout,这样就无需使用setX()方法,因为此布局会自动安排其子项。

所以你现在有两种可能来解决这个问题:

  1. 删除t2.setX(70)方法调用
  2. OR

    1. 将两个View添加到RelativeLayoutRelativeLayout不会自行安排子项,因此再次需要setX()方法。

答案 2 :(得分:0)

尽量不要使用t1.setX(20);t2.setX(70);

视图的位置应该通过它的父级来决定

答案 3 :(得分:0)

除了使用setX之外,最好使用RelativeLayout的对齐属性,因为您将RelativeLayout作为父布局。跳过中间的LinearLayout或将其更改为RelativeLayout。

试试这个:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
     RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);    
params.addRule(RelativeLayout.RIGHT_OF, textView1Id);
textView2Id.setLayoutParams(params);

因此,TextView 2将与TextView 1的右侧对齐。

希望这有帮助。

相关问题