简体   繁体   English

如何一个接一个地动态添加按钮

[英]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.我想使用 createButton 方法将随机位置上的特定数量的按钮添加到我的 Relativ 布局中。 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);
    }
}

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.如果您希望您的 UI 线程保持活动状态,您需要将它放在一个单独的线程中,并使用 AsyncTask 之类的东西,这样您的睡眠就不会冻结您的 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);
}

也许您只想使用简单的 for 循环?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM