Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding views dynamically in a for loop results in haphazard positioning - Android

Tags:

android

I am adding views dynamically to a relative layout (let's say container) in a for loop. There is some thing strange I am noticing.
When adding rows one below the other in a relative layout in a for loop, I see that the first time a few of the views are overlapping. But when I lock and unlock the screen, I can see that the views are placed correctly.

Should I be aware of something when adding views dynamically to a relative layout?

Edit
I have found a solution as to how to get rid of this (please check my answer). But I would be more than glad to accept an answer that analyses this problem and tells me why this happens.

I have simplified to code and the comments should give a good idea as to what I am doing.

int prev_id=ID_OF_THE_ELEMENT_ABOVE;

/*Empty RelativeView with width and height as MATCH_PARENT and WRAP_CONTENT respectively*/
RelativeLayout container=(RelativeLayout) findViewById(R.id.container);
while(ThereIsData){
                      /*GET THE DATA HERE THAT HAS TO BE ASSIGNED TO EACH TEXTVIEW*/
            ...


                        /* ADD TEXTVIEW #1 below prev_id/
            ...
            ...

                        /*ADD TEXTVIEW #2 (WITH BASELINE OF TEXTVIEW#
            ...
            ...

                        /*TEXTVIEW #3 (BELOW TEXTVIEW#1)*/
            ...
            ...                               

                        /*TEXTVIEW #4 (BELOW TEXTVIEW#2)*/
                        ...
            ...

                        /*ASSIGN THE ID OF TEXTVIEW#3 TO prev_id SO THAT 
                  IN THE NEXT ITERATION TEXTVIEW#1 CAN USE prev_id
                         */
                        prev_id=ID(TEXTVIEW#2);

            /*ADD TEXTVIEWS CREATED IN THIS ITERATION*/
             container.addView(TEXTVIEW#1);
                         container.addView(TEXTVIEW#2);
                         container.addView(TEXTVIEW#3);
                         container.addView(TEXTVIEW#4);                     
  }
like image 226
Ashwin Avatar asked May 11 '15 12:05

Ashwin


1 Answers

It is due to the fact that you are having a RelativeLayout with height as WRAP_CONTENT, and adding a view doesn't refresh the whole container at that time.. so as you answered you can add a line to measure the dimensions explicitly or invalidate the view to recreate it completely.

In any case LinearLayout would be better to opt-for as it will automatically arrange the children in horizontal or vertical manner and you can even add the new view in any place other than last position and it will automatically be updated..

like image 108
Ankit Bansal Avatar answered Oct 21 '22 21:10

Ankit Bansal