user3612383
user3612383

Reputation: 88

Android: addview not work in thread ( for while )

I use below code for 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");

After run this code , Logged is :

Before
Screen
After

But i want it :

Before
After
Screen

Actually runOnUiThread run after Thread is finish

But i want addView work in thread

Upvotes: 0

Views: 1386

Answers (1)

nuuneoi
nuuneoi

Reputation: 1798

I must say that it works perfectly like it should be.

If you want it to be:

Before
After
Screen

Try this:

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();

Upvotes: 1

Related Questions