android:layout_height屏幕大小的50%

Mar*_*zzi 45 size android android-layout android-linearlayout android-layout-weight

大家好我刚刚在LinearLayout中实现了ListView,但我需要定义LinearLayout的高度(它必须是屏幕高度的50%).

<LinearLayout
    android:id="@+id/widget34"
    android:layout_width="300px"
    android:layout_height="235px"
    android:orientation="vertical"
    android:layout_below="@+id/tv_scanning_for"
    android:layout_centerHorizontal="true">

    <ListView
        android:id="@+id/lv_events"
        android:textSize="18sp"         
        android:cacheColorHint="#00000000"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_scanning_for"
        android:layout_centerHorizontal="true">
    </ListView>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

这有可能吗?

我为一个按钮和一个EditText做了类似的事情,但似乎不适用于Layouts.

这是我的代码:

    //capture the size of the devices screen
    Display display = getWindowManager().getDefaultDisplay();
    double width = display.getWidth();

    //my EditText will be smaller than full screen (80%)        
    double doubleSize = (width/5)*4;
    int editTextSize = (int) doubleSize;

    //define the EditText 
    userName = (EditText) this.findViewById(R.id.userName);
    password = (EditText) this.findViewById(R.id.password);

    //set the size
    userName.setWidth(editTextSize);
    password.setWidth(editTextSize);
Run Code Online (Sandbox Code Playgroud)

谢谢!:)

Lef*_*nia 79

设置它的layout_height="0dp"*,View在它下面添加一个空格(或空白ImageView或只是一个FrameLayout)layout_height也等于0dp,并设置两个视图有一个layout_weight="1"

这将在填充屏幕时平均拉伸每个视图.由于两者具有相同的重量,每个将占据屏幕的50%.

*请参阅adamp的评论,了解其工作原理和其他真正有用的花絮.

  • 当您使用体重时,请记住,在测量完所有儿童视图后,体重会分配*剩余*空间.如果你只想依靠体重,你需要设置`layout_height ="0dp"`而不是`wrap_content`.你也可以明确地在LinearLayout上设置`weightSum`而不是添加空白视图来填充总重量. (20认同)

Emi*_*nin 6

这在xml中很容易做到.将顶部容器设置为LinearLayout并根据需要设置orientation属性.然后在那个地方内部有两个线性布局,它们在宽度和高度上都有"填充父级".最后,将这两个linearlayouts的weigth属性设置为1.


小智 6

这是我的android:layout_height = 50%活动:

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

    <LinearLayout
        android:id="@+id/alipay_login"
        style="@style/loginType"
        android:background="#27b" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/taobao_login"
        style="@style/loginType"
        android:background="#ed6d00" >
    </LinearLayout>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

样式:

<style name="loginType">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:layout_weight">0.5</item>
    <item name="android:orientation">vertical</item>
</style>
Run Code Online (Sandbox Code Playgroud)