Reputation: 1653
I need an advice...I want to create custom view group that will have different layout depending on size of this view.
An example:
Two views:
What I want:
Usually, I add views to my custom view in constructor. But I can't do it here because I don't know height of B in constructor. I know only height of A. So please advice me which callback method should I use...when height of B will be known so I can add all child views according this height.
Or if you know any other approach...please let me know...
Thank you very much!
Upvotes: 1
Views: 566
Reputation: 14404
You can use this code the get the actual height of main layout. Then you can use that height in a if-else or switch-case block to check the needed conditions.
public int getLayoutSize() {
// Get the layout id
final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
final AtomicInteger layoutHeight = new AtomicInteger();
root.post(new Runnable() {
public void run() {
Rect rect = new Rect();
Window win = getWindow(); // Get the Window
win.getDecorView().getWindowVisibleDisplayFrame(rect);
// Get the height of Status Bar
int statusBarHeight = rect.top;
// Get the height occupied by the decoration contents
int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
// Calculate titleBarHeight by deducting statusBarHeight from contentViewTop
int titleBarHeight = contentViewTop - statusBarHeight;
Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop);
// By now we got the height of titleBar & statusBar
// Now lets get the screen size
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
int screenWidth = metrics.widthPixels;
Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);
// Now calculate the height that our layout can be set
// If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also
layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
Log.i("MY", "Layout Height = " + layoutHeight);
// Lastly, set the height of the layout
FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
rootParams.height = layoutHeight.get();
root.setLayoutParams(rootParams);
}
});
return layoutHeight.get();
}
Upvotes: 0
Reputation: 116040
you should consider to put all views into a vertical linear layout which is in a scrollview , or better yet: use a single listView instead of layouts and scrollViews .
The reason is that it will handle the scrolling automatically if needed, depending on the available space on the screen and the size of your views.
Upvotes: 2