2

我有一个带有 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);

但我不确定这是一个好主意,因为它看起来有点复杂,可能在某些设备上效果不佳。有更好的建议吗?

4

1 回答 1

1

当你必须做这样的事情时,这清楚地表明你做错了什么。如果您真的需要 100 个网格中的按钮,也许您应该考虑使用 GridView 而不是 GridLayout 并通过简单的适配器将按钮加载到视图中。

于 2013-04-10T07:24:27.053 回答