Android:addview无法在线程中工作(for while)

时间:2015-03-12 10:51:23

标签: android multithreading

我在下面的代码中使用addview

final LinearLayout screenRL = (LinearLayout) findViewById(R.id.screenRL);
new Thread(new Runnable() {

            @Override
            public void run() {

                        for (int i = 0; i < 4; i++) {

                                    LayoutInflater inflater = getLayoutInflater();
                                    final View view = inflater.inflate(R.layout.dl, null);

                                    TextView txtTitleView = (TextView) view.findViewById(R.id.txtTitleView);
                                    txtTitleView.setText((i + 1) + ". Post");

                                    Log.i("Check", "Before : ");

                                    runOnUiThread(new Runnable() {

                                                public void run() {
                                                            Log.i("Check", "After");
                                                            screenRL.addView(view);

                                                }            
                                     });
                        }
            }
}).start();

Log.i("Check", "Screen");

运行此代码后,Logged为:

Before
Screen
After

但我想要它:

Before
After
Screen

实际上,在Thread完成后运行runOnUiThread

但我想在线程中使用addView工作

1 个答案:

答案 0 :(得分:1)

我必须说它完全像它应该的那样。

如果你想要它:

Before
After
Screen

试试这个:

final LinearLayout screenRL = (LinearLayout) findViewById(R.id.screenRL);
new Thread(new Runnable() {
    @Override
    public void run() {
        for (int i = 0; i < 4; i++) {
            LayoutInflater inflater = getLayoutInflater();
            final View view = inflater.inflate(R.layout.dl, null);

            TextView txtTitleView = (TextView) view.findViewById(R.id.txtTitleView);
            txtTitleView.setText((i + 1) + ". Post");

            Log.i("Check", "Before : ");

            runOnUiThread(new Runnable() {
                public void run() {
                    Log.i("Check", "After");
                    screenRL.addView(view);
                }            
            });
        }
        runOnUiThread(new Runnable() {
            public void run() {
                Log.i("Check", "Screen");
            }
        });
    }
}).start();