2

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 10 10 10 10 10 10 10 10

Any help in doing this "programtically" will be appreciated

3
  • Wow! what device are you using that has a screen large enough to display 80 clickable buttons? Commented Mar 23, 2010 at 9:36
  • @Matt Lacey: the soft keyboard is some 10-11 keys wide, depending on layout. OP wants to fit 8, so that doesn't sound unreasonable in comparison. and 10 buttons in height should be even easier. Commented Mar 23, 2010 at 12:54
  • The idea of 80 buttons on a screen still rings usability & design alarm bells for me though. Commented Mar 24, 2010 at 9:19

1 Answer 1

4

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);

   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.