Search code examples
javaandroidbuttondynamictimedelay

How to add Buttons dynamically one after another


I want to add a specific number of Buttons on random positions to my Relativ Layout with the method createButton. But the Buttons should appear one after another and not all at the same time and I have no idea how to achieve this.

Thanks all.

public void createButton(int amountOfButtons) {
    Random r = new Random();
    int i1 = r.nextInt(300);
    int i2 = r.nextInt(300);

    Button myButton = new Button(this);
    myButton.setText("Push Me");

    RelativeLayout ll = (RelativeLayout)findViewById(R.id.rela);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(50, 50);
    lp.setMargins(i1,i2,0,0);
    myButton.setLayoutParams(lp);
    ll.addView(myButton); 

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if (amountOfButtons > 1) {
        createButton(amountOfButtons-1);
    }
}

Solution

  • If you want your UI thread to remain active, you need to put this in a separate thread with something like an AsyncTask so that your sleep doesn't freeze your UI. Something like

    private class MyAsyncTask extends AsyncTask<Integer param, Void, Void>{
        private int time = 0;
        @Override
        protected Void doInBackground(Integer...time){
            this.time = time[0];
    
            try {
               Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
        }
    
        @Override
        protected void onPostExecute(Void result){
            createButton(time-1);
        }
    }
    

    Then do something like this in your activity

    private MyAsyncTask task;
    
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
    
        int time;
        // Some methodology to get the desired time
        createButton(time);
        new MyAsyncTask().execute(time -1);
    }
    

    With your method changed to

    public void createButton(int time) {
        Random r = new Random();
        int i1 = r.nextInt(300);
        int i2 = r.nextInt(300);
    
        Button myButton = new Button(this);
        myButton.setText("Push Me");
    
        RelativeLayout ll = (RelativeLayout)findViewById(R.id.rela);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(50, 50);
        lp.setMargins(i1,i2,0,0);
        myButton.setLayoutParams(lp);
        ll.addView(myButton); 
    
        if(time == 0) 
            return;
        else 
            new MyAsynCTask().execute(time);
    }