Android: creating a button in a line

Creates a dynamic button in one line

final LinearLayout layoutshape = (LinearLayout) findViewById(R.id.linearshape); a = new Button[10]; for (int i = 0; i < 10; i++) { a[i] = new Button(this); a[i].setText(""+i); a[i].setId(i); a[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); a[i].setBackgroundResource(R.drawable.background); layoutshape.addView(a[i]); } 

but I want this to be split into three lines. For example: if I have 30 buttons, then it needs to be displayed in 10 buttons in the 1st row, then in the next 10 in the second row and 10 in the third row

o / p:

b1 b2 b3 b4 b5

b6 b7 b8 b9 b10

b11 b12 b13 b14 b15

+4
source share
4 answers

First of all, set the orientation of the main layout (layoutshape) to vertical.

 for (int i = 0; i < i/10; i++) { LinearLayout row = new LinearLayout(this); 

set the orientation for the row horizontally.

 for (int i = 0; i < 30; i++) { a[i] = new Button(this); a[i].setText(""+i); a[i].setId(i); a[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); a[i].setBackgroundResource(R.drawable.background); row.addView(a[i]); } layoutshape.addView(row); } 
+2
source

You need at least n LinearLayout , where n is your number of lines. If you really want to use LinearLayout , then add your buttons using the following LayoutParams :

new LinearLayout.LayoutParams(0,LayoutParams.WRAP_CONTENT, 1/numButtonsInRow);

1/numButtonsInRow - button weight. For example, if you have 10 buttons in a row, each button will have a weight of 0.1 . If your layout is horizontal, set its width to 0, if it is set vertically, its height is 0.

In your case, you should probably use GridLayout or TableLayout .

+1
source

Create 3 LinearLayouts in the vertical layout LayarLayout "layoutshape". And then add buttons to the internal line layouts.

0
source

30 buttons look like a keyboard: http://developer.android.com/reference/android/inputmethodservice/Keyboard.html and the keyboard can be created via xml (see the SoftKeyboard example in the SDK, samples / android-10 / SoftKeyboard subdirectory).

If you really need buttons in 3 lines, my suggestion consists of 3 horizontal line layouts filled at runtime. But note that screen sizes are changing, and what is good on the phone may look ugly on the tablet.

0
source

All Articles