2017-02-11 20 views
-1

Я хочу добавить кнопки динамически. Я добавляю несколько кнопок динамически, но я хочу, чтобы добавить кнопки в следующей схеме:Как добавить кнопки динамически?

[BUTTON1] [BUTTON2] 
[BUTTON3] [BUTTON4] 
[BUTTON5] [BUTTON6] 

Это означает, что я хочу добавить только две кнопки в строке, которая динамически.

Я пробовал много вариантов. один из них:

LinearLayout ll = (LinearLayout) findViewById(R.id.buttonlayout); 
    Button[][] buttonArray = new Button[count][count]; 
    TableLayout table = new TableLayout(this); 
    for (int row = 0; row < count; row++) { 
     TableRow currentRow = new TableRow(this); 
     for (int button = 0; button < row; button++) { 
      Button currentButton = new Button(this); 
      // you could initialize them here 
      currentButton.setOnClickListener(this); 
      // you can store them 
      buttonArray[row][button] = currentButton; 
      // and you have to add them to the TableRow 
      currentRow.addView(currentButton); 
     } 
     // a new row has been constructed -> add to table 
     table.addView(currentRow); 
    } 

и, наконец, принимает эту новую таблицу и добавить его в макет. ll.addView(table);

Примечание: кол-во кнопок может быть случайной.

Как я могу это сделать?

+0

Все предыдущие попытки? или просто спрашивать? –

+2

, пожалуйста, найдите в google. Что вы пробовали до сих пор? –

+0

Да .. Я пробовал много .. Пожалуйста, помогите .. – Android

ответ

0

Создайте listview/recyclerview с настраиваемым элементом, который удерживает кнопку 2, как вы упомянули в своем вопросе, чем заполняет этот списокView с помощью кнопок (внутри адаптера, если элемент index% 2 == 0, он займет левую позицию, иначе правое положение).

0

ли что-то вроде этого:

LinearLayout ll_Main = new LinearLayout(getActivity()); 
    LinearLayout ll_Row01 = new LinearLayout(getActivity()); 
    LinearLayout ll_Row02 = new LinearLayout(getActivity()); 

    ll_Main.setOrientation(LinearLayout.VERTICAL); 
    ll_Row01.setOrientation(LinearLayout.HORIZONTAL); 
    ll_Row02.setOrientation(LinearLayout.HORIZONTAL); 

    final Button button01 = new Button(getActivity()); 
    final Button button02 = new Button(getActivity()); 
    final Button button03 = new Button(getActivity()); 
    final Button button04 = new Button(getActivity()); 

    ll_Row01.addView(button01); 
    ll_Row01.addView(button02); 

    ll_Row02.addView(button03); 
    ll_Row02.addView(button04); 

    ll_Main.addView(ll_Row01); 
    ll_Main.addView(ll_Row02); 

    button04.setVisibility(View.INVISIBLE); 
    button04.setVisibility(View.VISIBLE); 
0

попробовать этот код:

TableLayout layout = new TableLayout (this); 
    layout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT)); 

    for (int i=0; i<2; i++) { //number of rows 
     TableRow tr = new TableRow(this); 
     for (int j=0; j<2; j++) { //number of columns 
      Button b = new Button (this); 
      b.setText("Button:"+i+j); 
      b.setTextSize(10.0f); 
      b.setOnClickListener(this); 
      tr.addView(b, 30,30); 
     } 
     layout.addView(tr); 
    } 

Как ваш номер кнопки является случайным и можно использовать:

int total = 20; //random number of buttons 
int column = 3; //specify the column number 
int row = total/column; 

теперь используют column и row значение для динамического отображения кнопок

+0

добавит 4 кнопки. Я сказал, что количество кнопок может быть случайным. – Android

+0

проверить изменение .. – rafsanahmad007

1

Используйте вертикальный LinearLayout в формате XML. Затем программно создайте горизонтальную LinearLayout и добавьте кнопки в горизонтальной компоновке. Для каждой строки создайте и добавьте новую горизонтальную компоновку.

XML:

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

АКТИВНОСТЬ:

public class dynamicButtons extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.myLayout); 

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT); 

    int numberOfRows = 3; 
    int numberOfButtonsPerRow = 2; 
    int buttonIdNumber = 0; 


    final LinearLayout verticalLayout= LinearLayout)findViewById(R.id.buttonlayout); 

    for(int i=0;i<numberOfRows;i++){ 
     LinearLayout newLine = new LinearLayout(this); 
     newLine.setLayoutParams(params); 
     newLine.setOrientation(LinearLayout.HORIZONTAL); 
     for(int j=0;j<numberOfButtonsPerRow;j++){ 
      Button button=new Button(this); 
      // You can set button parameters here: 
      button.setWidth(20); 
      button.setId(buttonIdNumber); 
      button.setLayoutParams(params); 
      button.setText("Button Name"); 
      button.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View view) { 

        Intent is = new Intent(getApplicationContext(), someOtherApplication.class); 
        is.putExtra("buttonVariable", buttonIdNumber); 
        startActivity(is); 
       } 
      }); 

      newLine.addView(button); 
      buttonIdNumber++; 
     } 
     verticalLayout.addView(newLine); 

    } 
    } 
    }