我有一个带有 Button 和 GridLayout 的活动,其中有很多孩子。如果我在 onCreate() 中添加所有这些孩子,我的活动会出现在屏幕上,但有延迟:
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);
}
但我至少希望我的 Button 立即出现,所以我尝试将子项添加到线程中的网格中。经过实验,我得出了这个解决方案:
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);
但我不确定这是一个好主意,因为它看起来有点复杂,可能在某些设备上效果不佳。有更好的建议吗?