Android: layout_height 50% от размера экрана
Я только что реализовал ListView внутри LinearLayout, но мне нужно определить высоту 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>
Это возможно?
Я сделал нечто подобное для кнопки и EditText, но, похоже, не работает с макетами.
Это мой код:
//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);
Ответы
Ответ 1
Установите его layout_height="0dp"
*, добавьте в него пробел View
(или пустой ImageView
или просто FrameLayout
) с layout_height
, также равным 0dp
, и установите оба представления, чтобы иметь layout_weight="1"
Это будет растягивать каждый вид одинаково, поскольку он заполняет экран. Поскольку оба имеют одинаковый вес, каждый из них будет занимать 50% экрана.
* См. комментарий adamp, почему это работает, и другие действительно полезные лакомые кусочки.
Ответ 2
Это легко сделать в xml. Установите верхний контейнер как LinearLayout и установите атрибут ориентации, как вы пожелаете. Затем внутри этого места два линейных выхода, которые имеют "заполнение родителя" по ширине и высоте. Наконец, установите весовой атрибут этих двух линейных вычислений на 1.
Ответ 3
Это мой андроид: 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>
стиль:
<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>
Ответ 4
Лучший способ - использовать
layout_height = "0dp"
layout_weight = "0.5"
например
<WebView
android:id="@+id/wvHelp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5" />
<TextView
android:id="@+id/txtTEMP"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:text="TextView" />
WebView, TextView имеет 50% высоты экрана
Ответ 5
Вы должны сделать что-то вроде этого:
<LinearLayout
android:id="@+id/widget34"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
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_height="1"
android:layout_width="fill_parent"
android:layout_weight="0dp"
android:layout_below="@+id/tv_scanning_for"
android:layout_centerHorizontal="true"
/>
</LinearLayout>
Также используйте dp вместо px или читайте об этом здесь.
Ответ 6
Это так просто, если вы хотите разделить экран на две части по вертикали (верхние 30% + нижние 70%)
<LinearLayout
android:id="@+id/LinearLayoutTop"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2">
</LinearLayout>
<LinearLayout
android:id="@+id/LinearLayoutBottom"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
</LinearLayout>
Ответ 7
Чтобы убедиться, что высота представления составляет 50% экрана, мы можем создать два суб LinearLayouts в LinearLayout. Каждый из дочерних LinearLayout должен иметь android: layout_weight " 0,5, чтобы закрыть половину экрана
родительский LinearLAyout должен иметь " андроид: ориентация", установленный на вертикальный
.
.
вот код для вашей справки....
этот код содержит две кнопки высотой в пол экрана
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent">
<LinearLayout
android:layout_weight="0.5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:padding="10dp"
android:layout_weight="0.5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="button1"
android:id="@+id/button1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
/>
<Button
android:padding="10dp"
android:layout_weight="0.5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="button2"
android:id="@+id/button2"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
/>
</LinearLayout>
<LinearLayout
android:layout_weight="0.5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Ответ 8
Этот вид работал у меня.
Хотя FAB не плавает самостоятельно, но теперь он не толкается вниз.
Соблюдайте веса, указанные внутри LinearLayout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/andsanddkasd">
<android.support.v7.widget.RecyclerView
android:id="@+id/sharedResourcesRecyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="bottom|right"
android:src="@android:drawable/ic_input_add"
android:layout_weight="1"/>
</LinearLayout>
Надеюсь, что это поможет:)
Ответ 9
Чтобы достичь этого подвига, определите внешний линейный макет с помощью weightSum={amount of weight to distribute}
.
определяет максимальную сумму веса. Если не указано, сумма вычисляется путем добавления layout_weight всех дочерних элементов. Это может быть использовано, например, для того, чтобы дать одному ребенку 50% от общего доступного пространства, предоставив ему layout_weight 0.5 и установив weightSum в 1.0. Другим примером будет значение weightSum = 2, и если два ребенка установят layout_weight=1
то каждый получит 50% доступного пространства.
WeightSum зависит от количества дочерних элементов в родительском макете.
Ответ 10
Вы можете использовать android:weightSum="2"
в родительском макете в сочетании с android:layout_height="1"
в дочернем макете.
<LinearLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:weightSum="2"
>
<ImageView
android:layout_height="1"
android:layout_width="wrap_content" />
</LinearLayout>