以垂直和水平方式动态添加视图

时间:2014-04-11 22:33:50

标签: android android-layout

我正在尝试动态创建LinearLayout中的按钮,我想以纵向和横向方式添加它们。

首先,在布局中添加button A,如果button A与屏幕边缘之间有足够的空间,请在button B(水平)的右侧添加button A 。否则,请在button B下方(垂直方向)添加button A

我目前的布局:

<LinearLayout
    android:id="@+id/btn_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
</LinearLayout>
课堂上的

LinearLayout btnLayout = (LinearLayout) findViewById(R.id.btn_layout);
btnLayout.removeAllViewsInLayout();
for(Tag tag : tagList.getChildTags()) {
    Button button = new Button(this);
    button.setId(tag.getId());
    button.setText(tag.getName());
    btnLayout.addView(button);
}

在这种情况下,如果我将orientation设置为horizontal,则部分按钮不会显示(按屏幕截断),如果我设置为vertical,则会显示很糟糕。

有什么方法可以解决这个问题吗?提前谢谢大家!

1 个答案:

答案 0 :(得分:1)

你可以实现这一目标,但不能以微不足道的方式实现。我将解释我是如何做类似的事情(在我的情况下,我将TextView添加到TableRow),如果它们适合的话。

使用此方法,您必须使用TableLayout并使用TableRow添加Button。因此,您可以将"@+id/btn_layout" LinearLayout替换为TableLayout

首先,要获得屏幕的宽度,请使用以下内容:

final Display display = getWindowManager().getDefaultDisplay();
final Point size = new Point();
display.getSize(size);

final WindowManager.LayoutParams params = getWindow().getAttributes();

// Your screen's width will be stored within your params.width value    

您将使用它来了解当前Button当前TableRow是否仍适合屏幕宽度,或者必须将其添加到新屏幕中。所以现在,使用这样的东西来创建按钮:

int currentRowsWidth = 0;
TableLayout tl = (TableLayout) findViewById(R.id.my_table_layout);
TableRow currentRow = new TableRow();

for (Tag tag : tagList.getChildTags()) {
  Button button = new Button(this);
  button.setId(tag.getId());
  button.setText(tag.getName());

  // There's where you check whether it still fits the current `TableRow` or not
  if (currentRowsWidth + button.getWidth() < params.width) {
    currentRowsWidth += button.getWidth();
    currentRow.addView(button);
  }
  else {
    // It doesn't fit, add the currentRow to the table and start a new one
    tl.add(currentRow);
    currentRow = new TableRow();
    currentRow.addView(button);
    currentRowsWidth = button.getWidth();
  }
}

可能会发生这样的情况:一旦你离开循环,仍有Button要添加到currentView中,只需测试一下:

if (currentRow.getChildCound() > 0)
  tl.add(currentRow);

我是从头开始写的,所以有些东西可能不会在第一时间编译,但我希望你能理解。

相关问题