2014-04-15 104 views
-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); 
    } 
} 

回答

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

我已經嘗試了很多與此AsyncTask,但它不能正常工作... 我現在的主要問題是,AsyncTask只能執行一次(所以我不能使用像你建議的循環)。如果我生成一個AsyncTask的新實例,我不會一個接一個的按鈕,但所有的一起再次... – Oliver

+0

我已更新我的文章 – zgc7009

+0

對不起,我不能按照你的想法... 在onCreate你聲明變量時間的方法,但你沒有初始化它,那麼你想用時間調用createButton方法?!此外需要doInBackground方法,一個整數數組不是一個簡單的整數。如果我更改所有的錯誤應用程序甚至不啓動,我認爲計時器沒有太大的變化,但感謝您的幫助,毫無理由;) – Oliver

0

也許你只是想用簡單的for循環?

+0

雖然for循環不會保持其UI活躍。他可以添加按鈕,但在添加按鈕之前無法點擊它們 – zgc7009