[英]Set the width of relativelayout 1/3 the width of the screen?
我有一個如下的布局。 現在,我不想將相對布局的寬度設置為固定240 dp。 我想將相對布局的寬度設置為屏幕寬度的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>
在父級中使用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>
您必須使用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的比率。 文檔非常好。
帶有android:layout_orientation="horizontal"
的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.