如何一个接一个地动态创建按钮?

时间:2012-05-04 23:59:45

标签: android layout

我对Android开发者有一些经验,但我完全迷失在一个简单的任务中(至少看起来很简单)。

我有一个字符串的ArrayList,我想从布局列表中的字符串创建按钮。它不必是按钮 - 它可以是任何可点击的对象(带有文本)。

主要问题是我想要一个接一个地创建它们,当它们不适合屏幕时 - 应该创建新行。

普通线性布局可以按水平排列,但不会创建新线。 我也尝试了网格视图及其差不多 - 但它是一个网格,所以所有的colums都是相同的大小(但是文本可以不同,所以我不喜欢它。)

任何想法如何做到这一点? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

Android中没有流式布局。您必须实现自己的自定义布局(不是一件容易的事)或找到第三方流程布局。

答案 1 :(得分:1)

你可以尝试这样的事情。

// get the width of the screen
Display display = getWindowManager().getDefaultDisplay();
int windowWidth = display.getWidth();

// keep track of the width of your views on the current row
int cumulativeWidth = 0;

// the width of your new view
int newWidth = // insert some number here based on the length of text.

// get your main layout here
ViewGroup main = (ViewGroup)findViewById(R.id.YOUR_HOLDING_LAYOUT);

// the linear layout holding our views
LinearyLayout linear = null;
// see if we need to create a new row
if (newWidth + cumulativeWidth > windowWidth){
    linear = new LinearLayout(this);
    // set you layout params, like orientation horizontal and width and height. This code may have typos, so double check
    LayoutParams params = new LayoutParams(LinearLayout.FILL_PARENT, LinearLayout.WRAP_CONTENT);
   params.setOrientation(HORIZONTAL); // this line is not correct, you need to look up how to set the orientation to horizontal correctly.
    linear.setParams(params);
    main.addView(linear);
// reset cumulative width
cumulativeWidth = 0;
}

// no create you new button or text using newWidth
View newView = ... // whatever you need to do to create the view

linear.addView(newView);

//keep track of your cumulatinv width
cumulativeWidth += newWidth;