-2

メソッド createButton を使用して、ランダムな位置に特定の数のボタンを Relativ Layout に追加したいと考えています。しかし、ボタンはすべて同時に表示されるのではなく、次々に表示されるはずであり、これを実現する方法がわかりません。

皆さんありがとう。

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

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);
}
于 2014-04-15T20:43:09.750 に答える