【问题标题】:How to define a maximum or relative dimension in a view?如何在视图中定义最大或相对尺寸?
【发布时间】:2010-10-17 23:06:33
【问题描述】:

我的布局的一部分应该有两个组件:顶部的 ScrollView 和底部的 MapView。两个视图的大小都应该是父视图的一半。

我有父级的大小(当我已经有大小时,我正在切换到这个布局),但我不知道如何定义最大大小。此外,我认为有一个不需要定义大小的解决方案;例如,通过类似 Swing 风格的 GridLayout 或在某处定义权重,但我还没有找到任何听起来可行的方法。

我目前的方法是这里,它定义了最小尺寸,一旦 ScrollView 增长超过父级高度的一半,它显然会崩溃:

布局(父级是LinearLayout):

<LinearLayout
    android:id="@+id/result_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:visibility="gone"
    >

<ScrollView
    android:id="@+id/result_scroll"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    >

<LinearLayout
    android:id="@+id/result"
    android:layout_height="fill_parent"
    android:layout_width="wrap_content"
    android:paddingRight="?android:attr/scrollbarSize"
    android:orientation="vertical"
/>

</ScrollView>

<view class="com.google.android.maps.MapView"
    android:id="@+id/mapview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />

</LinearLayout>

还有代码,在我切换到它之后(totalWidth 是父级的宽度,viewHeight 是父级的一半高度):

LinearLayout.LayoutParams lp =
            new LinearLayout.LayoutParams(totalWidth, viewHeight);
scrollView.setLayoutParams(lp);

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    我的布局的一部分应该有两个组件:顶部的 ScrollView 和底部的 MapView。两个视图的大小都应该是父视图的一半。

    将它们放入LinearLayout。将每个的高度设置为0px。将每个的权重设置为1

    例如:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="0px"
        android:layout_weight="1"/>
    <Button
        android:layout_width="fill_parent"
        android:layout_height="0px"
        android:layout_weight="1"/>
    </LinearLayout> 
    

    此外,我认为有一种解决方案不需要定义尺寸...或在某处定义重量

    如果你不明确地告诉它它有多大(“定义大小”)或隐含地(“定义重量”),你怎么会知道它应该是“正好是父母”?

    【讨论】:

    • 我知道 Mark 可以胜任这项任务!没有太大的布局问题。 AFAIU,大多数Android布局都是在“最小高度”的概念下运行的,所以在测量之后,一个视图要么得到测量的高度,要么使用fill_parent获得整个父级的高度。
    • 至于您的第二个问题 - 逗号用于分隔示例,即“我认为有一个不需要定义大小的解决方案:[示例从此处开始] 使用 GridLayout,或定义重量”。对不起,那是模棱两可的。
    • 顺便说一句,我试过了,它有点工作,但没有最小高度。 ScrollView 最初的高度非常小,因此地图占据了大部分屏幕。随着 ScrollView 的增长,它占用了更多的空间,但从不超过高度的一半,这很好。我会接受您的回答,但是您对如何使最小尺寸为父母的一半有任何想法吗?
    • @EboMike:“ScrollView 最初的高度非常小,因此地图占据了大部分屏幕。” -- 见我上面添加的例子。 ScrollViewButton 各占屏幕的 50%。无论ScrollView 是空的还是比屏幕大,这都是正确的。
    • 我是个笨蛋。父 LinearLayout 将 wrap_content 作为其高度。现在它很完美。再次感谢,马克,你是任何与布局相关的大师!
    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 2014-03-07
    • 2020-08-15
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    相关资源
    最近更新 更多