[英]Android: How to create custom layout dependent on size
我需要一個建議...我想創建自定義視圖組,該視圖組將根據此視圖的大小而具有不同的布局。
一個例子:
兩種觀點:
我想要的是:
通常,我將視圖添加到構造函數中的自定義視圖中。 但是我不能在這里做,因為我不知道構造函數中B的高度。 我只知道A的高度。因此,請告知我應該使用哪種回調方法...何時知道B的高度,以便可以根據此高度添加所有子視圖。
或者,如果您知道其他任何方法,請告訴我...
非常感謝你!
您應該考慮將所有視圖放入在scrollview中的垂直線性布局中,或者更好的方法是:使用單個listView而不是layout和scrollViews。
原因是它將根據需要自動處理滾動,具體取決於屏幕上的可用空間和視圖的大小。
您可以使用此代碼獲取主布局的實際高度。 然后,可以在if-else或switch-case塊中使用該高度來檢查所需條件。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.