【问题标题】:Why aren't these TextView next to each other?为什么这些 TextView 不相邻?
【发布时间】:2015-02-15 23:47:40
【问题描述】:

我需要动态创建多个相邻的 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);

【问题讨论】:

    标签: android layout textview


    【解决方案1】:

    因为你正在使用:

    t2.setX(70);

    【讨论】:

      【解决方案2】:

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

      视图的位置应该由它的父级决定

      【讨论】:

        【解决方案3】:

        最好不要使用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 的右侧对齐。

        希望这会有所帮助。

        【讨论】:

          【解决方案4】:

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

          所以您现在有 2 种可能性来解决此问题:

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

          1. 改为将两个Views 添加到RelativeLayoutRelativeLayout 不会自行安排其子级,因此 setX() 方法再次成为必需。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-12-23
            相关资源
            最近更新 更多