How to give layout weight in RelativeLayout?

落爺英雄遲暮 提交于 2019-12-06 15:37:33
Coder55

You cannot use percentages to define the dimensions of a View inside a RelativeLayout. The best ways to do it is to use LinearLayout and weights, or a custom Layout.

Fore more information you can look at this question

If you want to stay with relative layout you can try to change the locations through the code. get the height and width of the outer layout using:

RelativeLayout rl = (RelativeLayout) findViewById(R.id.relative);
rl.getWidth();
rl.getHeight();

and then get the params of the layout you want to evenly distribute:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(50, 50); //here i created a new one with size 50,50

now you can set params.leftMargin and params.topMargin the way you want with any calculation.

params.leftMargin = rl.getWidth()/4 ;

for example will set the new layout at the 1/4 of the screen width

RelativeLayout is not a good choice because it doesn't provide a way you to evenly distribute children the way LinearLayout does. If you want something other than nested LinearLayouts, you can try using GridLayout (not GridView).

You cannot use layout_weight in RelativeLayout. Looking over your XML, your current layout is poorly structured which will lead to poor performance. I suggest that you use either GridLayout or Use your current LinearLayout but instead of assigning a LinearLayout to each number/character you can do something like this instead (Only for first row, but you get the idea):

`

<LinearLayout 
    android:id="@+id/LL_topRow"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="3"
    android:layout_margin="2dp">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textSize="64sp"
        android:clickable="true"
        android:gravity="center"
        android:text="1" />


    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textSize="64sp"
        android:clickable="true"
        android:gravity="center"
        android:text="2" />


    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:textSize="64sp"
        android:clickable="true"
        android:gravity="center"
        android:text="3" />

</LinearLayout>

<!-- Next LinearLayout Here for next row -->

`

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!