2016-07-25 67 views
0

我想在創建按鈕時逐個動態地將按鈕添加到網格佈局,但在我的情況下,按鈕是通過每次迭代逐個創建的,但它們一次添加到佈局當循環迭代完成時。
//這裏是代碼...如何在運行時將按鈕添加到佈局

public void Add_Button(View view){ 
     final MediaPlayer mediaPlayer=MediaPlayer.create(getApplicationContext(),R.raw.button_sound); 
     gridlayout= (GridLayout) findViewById(R.id.layout); 
     animation= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.scale_button); 
     for(int i=0;i<10;i++) { 
      Button button = new Button(MainActivity.this); 
      button.setText(i+1 + ""); 
      button.setPadding(10,10,10,10); 
      GridLayout.LayoutParams params = new GridLayout.LayoutParams(); 
      params.height=70; 
      params.width=70; 
      params.topMargin = 10; 
      params.leftMargin = 10; 
       *//after one 1 second i want to add button* 
      try { 
       Thread.sleep(1000); 

      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      button.setLayoutParams(params); 
      button.setAnimation(animation); 
      mediaPlayer.start(); 
      gridlayout.addView(button); 
     } 

     } 
+0

你的問題不明確。使用當前代碼有什麼問題? –

+0

檢查此問題http://stackoverflow.com/questions/13532084/set-rowspan-or-colspan-of-a-child-of-a-gridlayout-程序化可能有助於完整 –

+0

您不應該暫停主線程來實現一個簡單的動畫。 –

回答

0

一個簡單的解決問題的方法可以是使用視圖類的postDelayed

for(int i = 0; i < 10; i++) { 
    final Button button = new Button(MainActivity.this); 
    ... 
    gridlayoyt.postDelayed(new Runnable() { 

     @Override 
     public void run(){ 
      gridlayout.addView(button); 
     } 

    }, i * 1000); 

} 
+0

謝謝這就是我想要的 – Arsalan

0

您可以添加這樣

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags); 
layout.setOrientation(LinearLayout.VERTICAL); //Can also be done in xml by android:orientation="vertical" 

for (int i = 0; i < 3; i++) { 
    LinearLayout row = new LinearLayout(this); 
    row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 

    for (int j = 0; j < 4; j++ { 
     Button btnTag = new Button(this); 
     btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
     btnTag.setText("Button " + (j + 1 + (i * 4)); 
     btnTag.setId(j + 1 + (i * 4)); 
     row.addView(btnTag); 
    } 

    layout.addView(row); 
} 
相關問題