Подтвердить что ты не робот

Определение процентной ширины для LinearLayout?

Я хочу определить процентную ширину (70%) для LinearLayout, которая содержит некоторые кнопки, чтобы я мог ее центрировать и чтобы дочерние кнопки могли заполнить_parent. Вот картина, показывающая, что я имею в виду:

example

Мой текущий макет выглядит следующим образом:

<?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:id="@+id/layoutContainer" android:orientation="vertical">
    <LinearLayout android:layout_width="fill_parent"
        android:id="@+id/barContainer" android:orientation="horizontal"
        android:layout_height="40dp" android:background="@drawable/titlebackground">
        <ImageView android:id="@+id/barLogo" android:src="@drawable/titlelogo"
            android:layout_gravity="center_vertical" android:adjustViewBounds="true"
            android:layout_height="25dp" android:layout_width="wrap_content"
            android:scaleType="fitXY" android:paddingLeft="5dp"></ImageView>
    </LinearLayout>
    <TextView android:layout_height="wrap_content"
        android:layout_width="fill_parent" android:gravity="center_horizontal"
        android:id="@+id/searchTip" android:text="@string/searchTip"
        android:paddingTop="10dp" android:paddingBottom="10dp"></TextView>
    <LinearLayout android:layout_height="wrap_content"
        android:id="@+id/linearLayout1" android:orientation="vertical" android:layout_width="wrap_content">
        <Button android:text="Button" android:id="@+id/button1"
            android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <Button android:layout_width="wrap_content" android:id="@+id/button2" android:layout_height="wrap_content" android:text="Button"></Button>
        <Button android:layout_width="wrap_content" android:id="@+id/button3" android:layout_height="wrap_content" android:text="Button"></Button>
    </LinearLayout>
</LinearLayout>

В LinearLayout im, ссылающемся на идентификатор: linearLayout1. Как это сделать?

4b9b3361

Ответ 1

Вам нужно установить весовое свойство ваших элементов. Создайте три RelativeLayouts в качестве детей для LinearLayout и установите весы 0,15, 0,70, 0,15. Затем добавьте свои кнопки во второй RelativeLayout (тот, вес которого равен 0,70).

Вот так:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:id="@+id/layoutContainer" android:orientation="horizontal">
    <RelativeLayout
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="0.15">
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="0.7">

        <!-- This is the part that 70% of the total width. I'm inserting a LinearLayout and buttons.-->   
            <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical">

                <Button 
                    android:text="Button1"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
                </Button>
                <Button
                    android:text="Button2"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
                </Button>
                <Button
                    android:text="Button3"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
                </Button>

            </LinearLayout>
        <!-- 70% Width End-->

    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="0.15">
    </RelativeLayout>
</LinearLayout>

Почему весы 0,15, 0,7 и 0,15? Поскольку общий вес составляет 1 и 0,7 составляет 70% от общего количества.

Результат:

enter image description here

Редактировать. Благодаря @SimonVeloper для указания, что ориентация должна быть горизонтальной, а не вертикальной, а для @Andrew - указывать, что веса могут быть десятичными знаками вместо целых чисел.

Ответ 2

Надеюсь, это поможет

               

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="horizontal">

    <LinearLayout android:layout_width="0dip"
        android:layout_height="wrap_content" android:orientation="horizontal"
        android:id="@+id/linearLayout_dummy1" android:layout_weight=".15">
    </LinearLayout>


    <LinearLayout android:layout_height="wrap_content"
        android:id="@+id/linearLayout1" android:orientation="vertical"
        android:layout_width="0dip" android:layout_weight=".7">
        <Button android:text="Button" android:id="@+id/button1"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_gravity="center">
        </Button>
        <Button android:layout_width="wrap_content" android:id="@+id/button2"
            android:layout_height="wrap_content" android:text="Button"
            android:layout_gravity="center"></Button>
        <Button android:layout_width="wrap_content" android:id="@+id/button3"
            android:layout_height="wrap_content" android:text="Button"
            android:layout_gravity="center"></Button>
    </LinearLayout>

    <LinearLayout android:layout_width="0dip"
        android:layout_height="wrap_content" android:orientation="horizontal"
        android:id="@+id/linearLayout_dummy2" android:layout_weight=".15">
    </LinearLayout>

</LinearLayout>

(1) Установите layout_width в "0dip" (2) Установите layout_height в .xx(% вы хотите)

Ответ 3

Я знаю другое решение, которое работает с весом:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent" 
              android:weightSum="10" 
              android:gravity="center_horizontal">

    <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" 
            android:layout_weight="7">
    </LinearLayout>
</LinearLayout>

Ответ 4

Я думаю, что подход Эмиама прав. Но согласитесь с Саймоном Велопером (один из комментаторов ответа Эмиама): когда нам нужны кнопки в 70% ширины, мы должны использовать горизонтальную ориентацию для Linringayout и задавать ширину каждого Relativelayout до 0dip и их вес, как указано Поэтому я предлагаю эту версию:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@+id/layoutContainer" android:orientation="horizontal">
    <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="3">
    </RelativeLayout>
    <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="14">

            //This is where you add buttons. You can make them "fill_parent".
    </RelativeLayout>
    <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="3">
    </RelativeLayout>
</LinearLayout>

Ответ 5

В качестве последнего обновления для Android в 2015 году Google включила поддержку% support library

com.android.support:percent:23.1.0

Вы можете ссылаться на этот сайт, например, на его использование

https://github.com/JulienGenoud/android-percent-support-lib-sample

Gradle:

dependencies {
    compile 'com.android.support:percent:22.2.0'
}

В макете:

<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/top_left"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_alignParentTop="true"
        android:background="#ff44aacc"
        app:layout_heightPercent="20%"
        app:layout_widthPercent="70%" />

    <View
        android:id="@+id/top_right"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/top_left"
        android:background="#ffe40000"
        app:layout_heightPercent="20%"
        app:layout_widthPercent="30%" />


    <View
        android:id="@+id/bottom"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@+id/top_left"
        android:background="#ff00ff22"
        app:layout_heightPercent="80%" />
</android.support.percent.PercentRelativeLayout>

Ответ 6

Вы не можете определить ширину/высоту/поля/... используя проценты в вашем XML. Но то, что вы хотели бы использовать, это атрибут "вес", который является ИМО, наиболее похожим.

Другим способом было бы установить размеры программно после раздувания макета в коде, путем получения размера экрана и расчета необходимых полей.

Ответ 7

* Вы можете использовать свойства layout_weight. Если вы хотите взять 70% от ширины родителя, вы должны установить дочернее значение layout_width значение свойства 0dp, например android:layout_width="0dp" *

Ответ 8

Я решил аналогичную проблему, применив некоторые дополнения к LinearLayout следующим образом:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/app_background"
    android:padding="35dip">

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/black">

</RelativeLayout>
</LinearLayout>

Это, вероятно, не даст вам точного процента, но может быть легко окончено и избежать лишних ненужных элементов макета.

Ответ 9

Google представил новый API под названием PercentRelativeLayout

Добавьте скомпилированную зависимость, например

compile 'com.android.support:percent:22.2.0'

в том, что PercentRelativeLayout - это то, что мы можем сделать в процентах макета

Ответ 10

Использовать новую процентную библиотеку поддержки

compile 'com.android.support:percent:24.0.0'

См. ниже пример

<android.support.percent.PercentRelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
     <ImageView
         app:layout_widthPercent="50%"
         app:layout_heightPercent="50%"
         app:layout_marginTopPercent="25%"
         app:layout_marginLeftPercent="25%"/>
 </android.support.percent.PercentRelativeLayout>

Дополнительная информация Tutorial1 Tutorial2 Tutorial3