How to ensure views are set below the fold on a device.

Did you ever have a view that you needed to make sure started off below the screen so the user could scroll to it later?
Sounds weird but I had to do that for a designer’s crazy ass UI.
Wasn’t as simple as I first thought so I wanted to share the code.
Turns out that onLayout() doesn’t always work. you sometimes don’t get all of the dimensions for the views you’re interested in and it’s just a mess. I guess all the measures() for each view haven’t happened yet. Who knows, or rather who cares. It didn’t work so I had to find a way that did.

Turns out you can listen for layout change events by adding a listener to the ViewTreeObserver of a view, which notifies of many layout changes on your view. If you add a OnGlobalLayoutListener to the ViewTreeObserver of the view you’re interested in you are guaranteed to have gotten the measure() values at that point.
You can then use any way you want to set the position of your view. In my case I chose to use padding. Anyone have a better suggestion?

	ViewTreeObserver vto = bottomContainer.getViewTreeObserver();
	vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
	    @Override
	    public void onGlobalLayout() {
		Display display = getWindowManager().getDefaultDisplay();

		LinearLayout bottomContainer = (LinearLayout) findViewById(R.id.footer_container);
		ViewGroup profileBar = (ViewGroup) findViewById(R.id.profileBar);
		RelativeLayout sv = (RelativeLayout) findViewById(R.id.main);
		bottomContainer.setPadding(0, display.getHeight(), 0, 0);

		bottomContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
		bottomContainer.forceLayout();

	    }
	});

Leave a Reply

Your email address will not be published. Required fields are marked *