Установите ширину релятивирования на 1/3 ширины экрана?
У меня есть макет, как показано ниже. Теперь я не хочу устанавливать ширину относительного макета на фиксированный 240 дп. Я хочу установить ширину относительного макета на 1/3 ширины экрана. Возможно ли это сделать в XML файле. Если это невозможно, как я могу добиться этого с помощью java-кода?
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/fullscreen"
style="@style/translucent">
<RelativeLayout
android:layout_width="240dp"
android:layout_height="fill_parent"
android:layout_gravity="right"
android:gravity="center"
android:background="#88000000"
android:id="@+id/sidebar">
</RelativeLayout>
</FrameLayout>
Ответы
Ответ 1
используйте weightsum="3"
в родительском и layout_weight=1
в дочернем. Посмотрите эту ссылку
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/fullscreen"
style="@style/translucent"
android:orientation="horizontal"
android:weightSum="3">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_gravity="right"
android:gravity="center"
android:background="#88000000"
android:id="@+id/sidebar"
android:layout_weight="1"
>
</RelativeLayout>
<!-- other views, with a total layout_weight of 2 -->
</LinearLayout>
Ответ 2
Вы должны использовать LinearLayout
, чтобы получить ширину представления, чтобы быть третьим от его родительского вида.
Что-то вроде:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:background="#88000000">
</RelativeLayout>
<ViewGroup
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2">
</ViewGroup>
</LinearLayout>
Ключевым битом является отношение layout_weights. Документация довольно хороша.
Ответ 3
A LinearLayout
с android:layout_orientation="horizontal"
- это то, что вы хотите, вместе с весами.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
...all your stuff... />
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>