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

时间:2014-04-15 20:30:09

标签: java android button dynamic timedelay

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

谢谢大家。

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

2 个答案:

答案 0 :(得分:1)

如果您希望UI线程保持活动状态,则需要将其置于与AsyncTask类似的单独线程中,以便您的睡眠不会冻结您的UI。像

这样的东西
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);
    }
}

然后在你的活动中做这样的事情

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

将您的方法更改为

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

答案 1 :(得分:0)

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