Search code examples
androiduser-interfacebuttonimageviewdrawable

Android: Having custom buttons with an image while text aligned to the right and left


I have an imageView in which I using an OnClickListener, this way I have a custom button.

I also have text next to the imageView, however I want them to be able to click near the text as well.

I was wondering if it's possible to create a drawable file and just have the one button.

Here is what I have so far: https://i.sstatic.net/3BeR5.png


Solution

  • You can do this with a regular button. Set the images using drawableLeft and drawableRight attributes.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
    
        <Button
            android:id="@+id/backButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:drawableLeft="@drawable/ic_chevron_left_white_24dp"
            android:text="Back" />
    
        <Button
            android:id="@+id/nextButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:drawableRight="@drawable/ic_chevron_right_white_24dp"
            android:text="Next" />
    
    </RelativeLayout>
    

    You can also set android:background="@null" to remove the button outline and show only the text and the icon. It will look closer to your screen shot and the user can click on the icon or the text and the button will get the click.