繁体   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