0

I want to add button to grid-layout dynamically one by one as they are created but in my case the buttons are created one by one through each iteration but they are added to layout at once when the loop iteration complete.
// here is the code...

 public void Add_Button(View view){
        final MediaPlayer mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.button_sound);
        gridlayout= (GridLayout) findViewById(R.id.layout);
        animation= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.scale_button);
        for(int i=0;i<10;i++) {
            Button button = new Button(MainActivity.this);
            button.setText(i+1 + "");
            button.setPadding(10,10,10,10);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.height=70;
            params.width=70;
            params.topMargin = 10;
            params.leftMargin = 10;
              *//after one 1 second i want to add button*
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            button.setLayoutParams(params);
            button.setAnimation(animation);
            mediaPlayer.start();
            gridlayout.addView(button);
        }

        }
Arsalan
  • 23
  • 2
  • 9

1 Answers1

0

You can add like this

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"

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

    for (int j = 0; j < 4; j++ {
        Button btnTag = new Button(this);
        btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btnTag.setText("Button " + (j + 1 + (i * 4));
        btnTag.setId(j + 1 + (i * 4));
        row.addView(btnTag);
    }

    layout.addView(row);
}
Burak iren
  • 338
  • 3
  • 14