I need to retrieve the height of ScrollView
defined in a layout xml file during activity startup. Which is the best practice to implement this. I've tried placing the code inside onCreate()
, onStart()
and onResume()
. All gives height as 0 at startup.
Is there any methods like onFinishInflate()
for actvities?
Here is my code:
myScroll=(ScrollView) findViewById(R.id.ScrollView01);
int height=myScroll.getHeight();
You can do something like this:
Get a final reference to your ScrollView (to access in the onGlobalLayout() method). Next, Get the ViewTreeObserver from the ScrollView, and add an OnGlobalLayoutListener, overriding onGLobalLayout and get the measurements in this listener.
final ScrollView myScroll = (ScrollView)findViewById(R.id.my_scroll);
ViewTreeObserver vto = myScroll.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LayerDrawable ld = (LayerDrawable)myScroll.getBackground();
height = myScroll.getHeight();
width=myScroll.getHeight();
ViewTreeObserver obs = myScroll.getViewTreeObserver();
obs.removeOnGlobalLayoutListener(this);
}
});
see more in this thread:
How to retrieve the dimensions of a view?
You need to query view bounds after the layout was performed. Suggested place is onWindowFocusChanged(boolean)
. See this question for more information: How to get the absolute coordinates of a view
Also, if you dare to extend your Layout class, e.g. make a subclass of LinearLayout
etc., you can override it's onLayout() in this manner:
@Override
public void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
myScroll=(ScrollView) findViewById(R.id.ScrollView01);
int height=myScroll.getHeight();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With