2012-06-28 3 views
6

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

Assign width to half available screen width declaratively

Как сделать то же самое в относительном макете? Вот код: Попробуйте 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> 
+0

, что вы на самом деле хотите, чтобы нырнул в макет экрана или это виджеты – MobileEvangelist

+0

сделать вид вид макета который совместим со всеми размерами экрана. – dreamhigh

+0

Я не понимаю ваш вопрос. связанный вопрос состоит в том, чтобы разделить вид на две половины. у вас есть дюжина просмотров в вашей линейной компоновке. что вы пытаетесь сделать? – njzk2

ответ

4

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

<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> 
+0

Так что мне придется использовать линейный макет несколько раз? У меня почти более 5 строк, похожих на нее в относительной компоновке. – dreamhigh

+0

Есть одна относительная компоновка, внутри которой вы можете иметь линейную компоновку, которая содержит всю строку, пусть она будет одной, двумя или 100. –

+0

не работает :( – dreamhigh

1
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. Havent попробовал myslef для RelativeLayout. Дать ему шанс. Комментарий, если он не работает.

-1
<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» и обеспечивают вес (указать область, которая будет занимать).

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

+0

Нет. Каждый элемент имеет идентификатор. Не имеет значения. – dreamhigh

+0

android: layout_weight = "1" не работает в RelativeLayout –

51

Это приятное обходное решение, если вам нужна половина, при использовании 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> 

Его действительно умные.

+0

Я согласен, очень умный. Мне было бы интересно узнать, действительно ли это происходит быстрее при рендеринге, чем при использовании LinearLayout. – zarazan

+0

Idk, вероятно, нет, но в более общем виде, но если youre используя относительный макет для начала, это было бы быстрее, потому что вы вставляете вложенные макеты – urSus

2

В дополнение к ответу Ursus «s, то лучше использовать Space класс вместо View:

<Space android:id="@+id/fakeView" 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:layout_centerInParent="true"/> 
+1

Я не согласен. Пространство доступно только для api14 +, что делает его практически бесполезным, если вы хотите настроить таргетинг на широкий диапазон устройств. – njzk2

+0

хорошо, api14 + 4.0 + и согласно последней таблице распределения платформы (http://goo.gl/fmFDJw), количество устройств с h api <14 теперь составляет около 15%, что уже почти незначительно – Dmide

+2

, если вы обнаружите, что 15% незначительно, хорошо для вас. также эта диаграмма измеряет только устройства с доступом к магазину воспроизведения Google, что далеко не все устройства. – njzk2

Смежные вопросы