-2

我想使用 createButton 方法将随机位置上的特定数量的按钮添加到我的 Relativ 布局中。但是按钮应该一个接一个地出现,而不是同时出现,我不知道如何实现这一点。

谢谢大家。

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);
    }
}
4

2 回答 2

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. 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);
}
于 2014-04-15T20:43:09.750 回答
0

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

于 2014-04-16T13:46:26.640 回答