2013-04-10 23 views
2

我有一個Button和一個GridLayout與許多孩子的活動。如果我添加所有這些兒童的onCreate()出現在我的活動具有滯後性在屏幕上:Android:在一個單獨的線程中添加許多孩子到一個佈局

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    LinearLayout main = new LinearLayout(this); 
    main.setOrientation(LinearLayout.VERTICAL); 

    Button button = new Button(this); 
    button.setText("test"); 
    main.addView(button); 

    GridLayout testGrid = new GridLayout(this); 
    testGrid.setColumnCount(5); 
    for (int i = 0; i < 100; i++) 
     testGrid.addView(new Button(this)); 
    main.addView(testGrid); 

    setContentView(main); 
} 

但我想至少我的按鈕移到立即出現,所以我儘量給孩子添加到網格中線。經過實驗,我來到這個解決方案:

final GridLayout testGrid = new GridLayout(this); 
    testGrid.setColumnCount(5); 
    main.addView(testGrid); 
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
     public void run() { 
      new Thread(new Runnable() { 
       public void run() { 
        for (int i = 0; i < 100; i++) 
         MyActivity.this.runOnUiThread(new Runnable() { 
          @Override 
          public void run() { 
           testGrid.addView(new Button(testGrid.getContext())); 
          } 
         }); 
       } 
      }).start(); 
     } 
    }, 1); 

但我不知道這是一個好主意,因爲它看起來有點複雜,可能不會在某些設備上很好地工作。有更好的建議嗎?

回答

1

當你必須這樣做時,這是一個明確的跡象表明你做錯了什麼。如果你真的需要一個網格中的100個按鈕,也許你應該考慮使用GridView而不是GridLayout,並通過一個簡單的適配器將按鈕加載到視圖中。

+0

謝謝你的建議,但我不想使用GridView,因爲它在滾動時有一些滯後。 – netimen 2013-04-10 07:32:40

相關問題