Search code examples
androidandroid-layoutandroid-buttonandroid-relativelayoutandroid-percent-library

Fix Layout issue


Scenario: I've four buttons arranged Relative Layout. These button's text varies through the app life which makes button shrink or expand according to text length. Using: RelativeLayout.getChildAt().setText();

Q1) But I require the each button to occupy 40% of screen width but with varying height. Q2) And in particular my code requires to access buttons using getChildAt().

What Layout type should I use to replace RelativeLayout to set Button's width to 40% of screen width and in particular so I can access these Buttons using getChildAt()? SomeLayout.getChildAt(); so that the Layout is immediate parent of Buttons.

    <RelativeLayout android:id="@+id/buttonRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:layout_margin="10dp">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/optionButton1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/optionButton2"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/optionButton3"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/optionButton4"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

Solution

  • You are actually just in luck. Android just released a new percent support library. They don't have documentation yet, but here is a good sample project that you can use to see how to go about using the library. It basically allows you to size view widgets by percentage of the screen.

    https://github.com/JulienGenoud/android-percent-support-lib-sample

    And here are two articles talking about it as well:

    http://www.androidauthority.com/using-the-android-percent-support-library-630715/

    http://inthecheesefactory.com/blog/know-percent-support-library/en