开发者

Help: 8 X 10 2-dimensional array of buttons in android

i am stuck with a problem creating buttons dynamically in android. This is what i want to do-

I want to create 8 x 10 array of buttons. Since declaring 80 buttons in main.xml isn't efficient, I want to do this in the program itself. The biggest problem is placing/aligning the buttons like a grid. I can create button objects but how do I align them in the program?

Button b = new Button(this); 
b.setId(i);
b.setText("Button " + i); 

Like this-

1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
.
.
.
10 10 1开发者_运维百科0 10 10 10 10 10 10 10

Any help in doing this "programtically" will be appreciated


You need a container to place them all in:

<LinearLayout
    android:id="@+id/llContainer"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

And then I'd add them as 10 separate 'rows':

LinearLayout container = (LinearLayout) findViewById(R.id.llContainer);

for(int i = 0; i < 10; i++) {
   LinearLayout row = new LinearLayout(this, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
   container.addView(row);

   for(int x = 0; x < 8; x++) {

      Button btn = new Button(this, new LayouParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
      btn.setText(i + ':' + x);

      row.addView(btn);

   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜