So I have a bit of confusion with trying to set the background drawable of a view as it is displayed. The code relies upon knowing the height of the view, so I can't call it from onCreate()
or onResume()
, because getHeight()
returns 0. onResume()
seems to be the closest I can get though. Where should I put code such as the below so that the background changes upon display to the user?
TextView tv = (TextView)findViewById(R.id.image_test);
LayerDrawable ld = (LayerDrawable)tv.getBackground();
int height = tv.getHeight(); //when to call this so as not to get 0?
int topInset = height / 2;
ld.setLayerInset(1, 0, topInset, 0, 0);
tv.setBackgroundDrawable(ld);
by using the global listener, you may run into an infinite loop.
i fixed this by calling
inside of the onGlobalLayout method within the listener.
So summarily, 3 ways to handle size of view.... hmmm, maybe so!
1) As @Gautier Hayoun mentioned, using OnGlobalLayoutListener listener. However, please remember to call at the first code in listener:
listViewProduct.getViewTreeObserver().removeOnGlobalLayoutListener(this);
to make sure this listener won't call infinitely. And one more thing, sometime this listener won't invoke at all, it because your view has been drawn somewhere you don't know. So, to be safe, let's register this listener right after you declare a view in onCreate() method (or onViewCreated() in fragment)2) If you want to do something right after the view has been drawn and shown up, just use post method (of course you can get the size here, since your view was drawn completely already). For example,
More over, you can use postDelay with the same purpose, adding a little delay time. Let's try it yourself. You will need it sometime. For prompt example, when you want to scroll the scroll view automatically after adding more items into scroll view or expand or make some more view visible from gone status in scroll view with animation (it means this process will take a little time to show up everything). It will definitely change scroll view's size, so after scroll view is drawn, we also need to wait a little time for get an exact size after it adds more view into it. This's a high time for postDelay method to come to rescue!
3) And if you want to set up your own view, you can create a class and extend from any View you you like which all have onMeasure() method to define size of the view.
Hope this helps,
Mttdat.