在scrollview中的linear_layout中使用match_parent的两个视图

时间:2015-08-23 15:09:24

标签: android android-layout scrollview android-linearlayout

是否可以在scrollview中的linear_layout内有两个与活动屏幕高度相同的视图?我试着这样做:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">
<LinearLayout android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <Button android:layout_width="match_parent"
        android:layout_height="match_parent"/>   
    <Button android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
</ScrollView>

唯一出现一个带有屏幕高度的按钮。另一个按钮似乎消失了。

我认为使用属性match_parent来获得两个视图是矛盾的。

但是,我希望使用xml获得与可用屏幕大小相同的两个视图,并使用scrollview使两个视图都可访问。我知道它可以通过java完成,但我想要一个xml的答案。

2 个答案:

答案 0 :(得分:0)

Linear Layout中你必须定义两件事......

1。android:orientation="vertical"

2. android:weightSum="2" weightSum是其父元素布局中所有元素的总和。它允许您定义元素在布局中应占用的宽度/高度的比例。

  

有关详细信息,请转至weightSum

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/textView1"
android:fillViewport="true" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="2" >

    <Button
        android:id="@+id/but1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="but 1" />

    <Button
        android:id="@+id/but2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="but 1" />
  </LinearLayout>

 </ScrollView>

输出

enter image description here

答案 1 :(得分:0)

您无法仅在XML中实现此目的。

由于android支持多种屏幕尺寸,在运行时你需要检查每个设备,每个设备的高度可以像这样计算

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;

使用上面的代码,您将获得屏幕的高度,您需要在运行时将dp中的高度设置为您的视图。

在两个按钮的活动中执行此操作:

        // get view you want to resize
        Button but1= (Button) findViewById(R.id.but1); 


        LinearLayout.LayoutParams listLayoutParams = new LinearLayout.LayoutParams(
                    height , LinearLayout.LayoutParams.MATCH_PARENT);
        but1.setLayoutParams(listLayoutParams);