簡體   English   中英

Android:如何根據尺寸創建自定義布局

[英]Android: How to create custom layout dependent on size

我需要一個建議...我想創建自定義視圖組,該視圖組將根據此視圖的大小而具有不同的布局。

一個例子:

兩種觀點:

  • 視圖A:高度至少為50dp的子視圖
  • 視圖B:我的自定義視圖在垂直方向上延伸LinearLayout,高度為200 dp

我想要的是:

  1. 當我將2個視圖A插入到視圖B中時:
    • 我想將這兩個視圖A拉伸到100 dp。 因此,B將是帶有2個子級的常見線性布局。
  2. 當我將5個視圖A插入視圖B時:
    • 我想將滾動視圖添加到B。所有5個視圖A都將在此滾動視圖內,並且它們的高度將為50 dp。

通常,我將視圖添加到構造函數中的自定義視圖中。 但是我不能在這里做,因為我不知道構造函數中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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM