Search code examples
androidandroid-layoutandroid-linearlayoutandroid-relativelayout

How can I nest a linear layout inside a relative layout to achieve the desired UI experience?


I am trying to get the following look (screenshot from my iOS app) on the Android version of my app.

Screenshot from my iOS app

I have defined my layout file as follows in Android:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <EditText
        android:id="@+id/postTextTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/shareLILayout"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:gravity="top|left|start"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

    <LinearLayout 
        android:id="@+id/shareLILayout"
        android:layout_alignParentBottom="true"
        android:background="#999999"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:orientation="horizontal" >
        
        <ImageButton
            android:contentDescription="@string/li_btn_desc"
            android:id="@+id/postToLIButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="5dp"
            android:layout_marginBottom="5dp"
            android:background="@android:color/transparent"
            android:src="@drawable/linkedin_switch_off" />
                
        <TextView
            android:id="@+id/postToLITextView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/share_on_linkedin"
            android:layout_gravity="center_vertical"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textSize="14sp" />

    </LinearLayout>
</RelativeLayout>

If I swap my ImageButton and TextView above, my app just crashed with a RuntimeException! Also I am not able to center the text so that its aligned to the center of the button. What am I doing wrong?


Solution

  • Simply swap the ImageButton and TextView order. Your runtime error is either unrelated or is caused by the need to clean your project before you need to redeploy it (sometimes resource IDs get funky). Also use android:gravity="center_vertical" for you TextView to center it properly