Отрегулируйте ширину до половины экрана

Я наткнулся на эту ссылку:

Декларативно назначить ширину половине доступной ширины экрана

Как сделать то же самое в относительной компоновке? Вот код: Пробуем linearlayout внутри относительного макета. Но это не работает.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bg" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/button5"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="14dp"
            android:layout_weight="1"
            android:text="Button" />

        <Button
            android:id="@+id/button6"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_weight="1"
            android:text="Button" />

        <Button
            android:id="@+id/button4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_weight="1"
            android:text="UID"
            android:textColor="#ffe5f1f1" />

        <EditText
            android:id="@+id/editText1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#ffe5f1f1"
            android:hint="Enter UID"
            android:inputType="number"
            android:shadowColor="5"
            android:textColor="#ff009999"
            android:textStyle="bold"
            android:typeface="monospace" >

            <requestFocus />
        </EditText>



    <Button
        android:id="@+id/button7"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
            android:layout_weight="1"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="18dp"
        android:text="Button" />

    <Button
        android:id="@+id/button8"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button7"
            android:layout_weight="1"
        android:layout_marginTop="16dp"
        android:text="Button" />

    <Button
        android:id="@+id/button9"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
            android:layout_weight="1"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button8"
        android:layout_marginTop="17dp"
        android:text="Button" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="50"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_weight="1"
        android:background="#ffe5f1f1"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="number"
        android:inputType="textPersonName"
        android:textColor="#ff009999"
        android:textStyle="bold"
            android:layout_weight="1"
        android:typeface="monospace" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:ems="10"
            android:layout_weight="1"
        android:inputType="number" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button7"
        android:layout_alignBottom="@+id/button7"
        android:layout_alignParentRight="true"
        android:ems="10"
            android:layout_weight="1"
        android:inputType="phone" />

    <EditText
        android:id="@+id/editText5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button8"
        android:layout_alignBottom="@+id/button8"
        android:layout_alignParentRight="true"
        android:ems="10"
            android:layout_weight="1"
        android:inputType="textPersonName" />

    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button9"
        android:layout_alignBottom="@+id/button9"
        android:layout_alignLeft="@+id/editText5"
            android:layout_weight="1"
        android:text="Male" />

    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/radioButton2"
        android:layout_alignBottom="@+id/radioButton2"
        android:layout_alignParentRight="true"
            android:layout_weight="1"
        android:text="Female" />

    <Button
        android:id="@+id/button10"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button9"
        android:layout_marginTop="31dp"
            android:layout_weight="1"
        android:text="Button" />

    <Spinner
        android:id="@+id/spinDept"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button10"
        android:layout_alignBottom="@+id/button10"
        android:layout_alignLeft="@+id/radioButton2"
        android:layout_alignParentRight="true"
        android:layout_weight="1"
        android:background="#ff009999" />
   </LinearLayout>
</RelativeLayout>

person Community    schedule 28.06.2012    source источник
comment
что вы на самом деле хотите погрузиться в макет экрана или его виджеты   -  person MobileEvangelist    schedule 28.06.2012
comment
сделать макет формы, который совместим со всеми размерами экрана.   -  person    schedule 28.06.2012
comment
я не понимаю вашего вопроса. связанный вопрос касается разделения представления на 2 половины. у вас есть дюжина просмотров в вашем линейном макете. что ты пытаешься сделать?   -  person njzk2    schedule 21.07.2014


Ответы (6)


Это хороший обходной путь, если вам нужна именно половина при использовании RelativeLayout. Что вы делаете, так это создаете фальшивое невидимое представление с центром в родительском элементе, а левая кнопка должна быть alignParentLeft и alignRight для этого фальшивого представления, а правая кнопка — наоборот.

<RelativeLayout 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">

   <View android:id="@+id/fakeView"
       android:layout_width="0dp"
       android:layout_height="0dp" 
       android:layout_centerInParent="true"/>
   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignRight="@id/fakeView"
       android:layout_alignParentLeft="true"
       android:text="Left"/>

   <Button 
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@id/fakeView"
      android:layout_alignParentRight="true"
      android:text="Right"/>

</RelativeLayout>

Это действительно умно.

person urSus    schedule 08.07.2013
comment
Согласен, очень умно. Я хотел бы знать, действительно ли это быстрее при рендеринге, чем при использовании LinearLayout. - person zarazan; 10.08.2013
comment
Не знаю, наверное, нет, но в более общем виде, но если вы используете относительный макет для начала, это будет быстрее, потому что вы удаляете вложенные макеты - person urSus; 11.08.2013

Оберните то же самое с относительным макетом, который должен работать для вас.

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <Button android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="somebutton">

    <TextView android:layout_width="fill_parent"
            android:layout_height="Wrap_content"
            android:layout_weight="1">
</LinearLayout>
person RPB    schedule 28.06.2012
comment
Значит, мне придется несколько раз использовать Linear layout? У меня есть почти более 5 строк, похожих на него в относительной раскладке. - person ; 28.06.2012
comment
Имейте один относительный макет, внутри которого вы можете иметь линейный макет, который содержит всю вашу строку, пусть это будет один, два или 100. - person RPB; 28.06.2012

В дополнение к ответу urSus лучше использовать Пробел вместо View:

   <Space android:id="@+id/fakeView"
       android:layout_width="0dp"
       android:layout_height="0dp" 
       android:layout_centerInParent="true"/>
person Dmide    schedule 21.07.2014
comment
Я не согласен. Пространство доступно только для api14+, что делает его практически бесполезным, если вы хотите настроить таргетинг на широкий спектр устройств. - person njzk2; 21.07.2014
comment
ну, api14+ — это 4.0+, и, согласно последней диаграмме распределения платформы (goo.gl/fmFDJw), количество устройств с api ‹14 сейчас около 15%, что уже почти ничтожно - person Dmide; 21.07.2014
comment
если вы обнаружите, что 15% незначительны, хорошо для вас. также на этой диаграмме измеряются только устройства с доступом к магазину Google Play, а это далеко не все устройства. - person njzk2; 21.07.2014

    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();
    plannerEditLayout = (RelativeLayout) findViewById(R.id.plannerLayoutEdit);
    plannerEditLayout.setGravity(Gravity.CENTER_VERTICAL);
    plannerEditLayout.setLayoutParams(new RelativeLayout.LayoutParams(
            (width / 2), height));

Я использую тот же код для LinearLayout. Не пробовал сам для RelativeLayout. Дать ему шанс. Прокомментируйте, если это не работает.

person Swayam    schedule 28.06.2012

Попробуйте layout_weight на 1 и layout_width на fill_parent вот так,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/main_layout"
    android:orientation="vertical"
    android:padding="10dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">
           
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">
            
        </LinearLayout>
    </LinearLayout>
</LinearLayout> 
person Codemaker    schedule 16.02.2021

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <Button android:layout_width="match_parent"
             android:id="@+id/button"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="somebutton">

    <TextView android:layout_width="match_parent"
             android:id="@+id/textview"
            android:layout_height="Wrap_content"
            android:layout_weight="1">
</LinearLayout>

В приведенном выше примере используется LinearLayout, установите для виджета layout_width значение «match_parent» и укажите вес (чтобы указать занимаемую область).

Это решает вашу проблему.

person MobileEvangelist    schedule 28.06.2012
comment
Неа. Каждый элемент имеет определенный идентификатор. Неважно с этим. - person ; 28.06.2012