【问题标题】:Android set margin in for cycleAndroid 为循环设置边距
【发布时间】:2023-04-09 20:52:01
【问题描述】:

我正在尝试以编程方式将一些 TextView 放入我的活动中。问题是我无法设置它们的边距(上边距),所以它们之间有一些空间。

XML 布局结构如下:

<ScrollView>

    <RelativeLayout_1>

        <RelativeLayout_2>

            <TextView/>

            <EditText/>
        </RelativeLayout>
    </RelativeLayout>

</ScrollView>

我省略了所有不必要的信息。

然后在我的活动中我做

    mLayout = (RelativeLayout) findViewById(R.id.relative_layout);

    RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    relativeParams.addRule(RelativeLayout.ALIGN_LEFT, R.id.handicap_layout);
    relativeParams.addRule(RelativeLayout.BELOW, R.id.handicap_layout);

    TextView[] texts = new TextView[6];

    for(int i=0; i<6; i++) {
        texts[i] = new TextView(MyActivity.this);
        texts[i].setText("Text " + (i+1));
        texts[i].setTextSize(20);
        relativeParams.setMargins(0, 10+(10*i), 0, 0);   /* trying to increase the margin */
        texts[i].setLayoutParams(relativeParams);
        mLayout.addView(texts[i]);
    }

mLayout 指的是RelativeLayout_1,handicap_layout 指的是RelativeLayout_2。

问题是边距没有增加,TextView 显示在另一个之上。

有人有解决办法吗?谢谢!

编辑:已解决

好的,我设法解决了这个问题:LayoutParams 必须在 inside for 循环中声明。 谢谢。

【问题讨论】:

    标签: android android-relativelayout margins


    【解决方案1】:

    获取一个 textview xml 文件。在那拿利润。一旦完成,膨胀该文本视图。

    TextView itemview = (TextView)getLayoutInflater().inflate(R.layout.equipment_item, null);
    

    完成后,将您的文本设置为该布局。

    我想你已经找到了正确的相对布局。然后将该 itemview 添加到如下的相对布局中。

    equipmentdetails_layout.addView(itemview);
    

    然后您可以获得边距。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      相关资源
      最近更新 更多