Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Layout size at application startup

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();
like image 484
JiTHiN Avatar asked Oct 24 '12 10:10

JiTHiN


2 Answers

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?

like image 179
Anup Cowkur Avatar answered Nov 01 '22 12:11

Anup Cowkur


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();
}
like image 28
user1410657 Avatar answered Nov 01 '22 13:11

user1410657