Android:设计扩展到宽度

时间:2012-04-14 18:55:45

标签: android xml layout

我试图找出多种屏幕尺寸/密度/等的设计。我想" dp"是我的答案,但它没有像我想象的那样工作。

这是我想要做的事情:

我有一个页眉和页脚部分,用于保持静态的菜单项。然后我在2之间有一个ScrollView。在ScrollView中有几个"块"显示各种信息。我希望这些块始终扩展到屏幕的整个宽度。我希望这些块的高度能够适当地缩放以保持适当的1:1 - >高度:宽度比例。我还希望TextViews / Images / Buttons / etc能够缩放并保持它们在块中的位置。如果块的高度对于屏幕来说太大了,那就是ScrollView所在的位置。如果它们适合,那也可以。我主要想扩展到宽度,并在必要时让用户滚动。

目前,如果屏幕变得更宽,则块变得非常宽,但不要缩放高度以匹配它们。

这是我的XML布局代码的基本概念(简化为可读性)。另请注意,每个块可能具有不同的大小。我不是在寻找"占据25%"解。这些块具有相当复杂且完全不同的布局。

<LinearLayout>
    <RelativeLayout>Header stuff</RelativeLayout>

    <ScrollView> //height and width = match_parent width lower priority than header/footer

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="???" //Had been using a specified "dp" value but that didn't work like I thought. What goes here?
        >
                Block#1 with lots of TextViews, ImageViews and Buttons...etc
        </RelativeLAyout>

        <RelativeLayout>
                Block#2
        </RelativeLAyout>

        <RelativeLayout>
                Block#3... etc
        </RelativeLAyout>

    </ScrollView>

    <RelativeLayout>Footer stuff</RelativeLayout>

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

实现视图的“完美”1:1比率(或其他预定义比率)的一种方法是创建自定义扩展,并覆盖onMeasure()方法。在您的情况下,您可能希望使用SquareRelativeLayout方法的onMeasure()看起来像这样:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    setMeasuredDimension(width, width);
}

编辑: 如果你想要一个自定义比例,你可以在某个地方定义它并像这样测量你的视图:

float ratio = 0.5f;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    setMeasuredDimension(width, ratio*width);
}

如果您知道如何创建自己的xml属性,则可以添加ratio属性并从中获取它,这意味着您不必为每个不同的比率创建新视图。