Home » Android » How to create a custom shape of a button but keep it clickable and focusable

How to create a custom shape of a button but keep it clickable and focusable

Posted by: admin November 1, 2017 Leave a comment

Questions:

I want to make a button to have a custom shape, but when I tried the shape changed, but it wasn’t clickable/focusable, how do I do it?

Answers:

You can do it by two ways,

  1. Set any layout/button with shape drawable and add android:foreground="?attr/selectableItemBackground" in XML

  2. Set the Style attribute in button.
    style="@style/buttonTheme" in its XML and define
    <style name="buttonTheme" parent="Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/#000000</item>
    in /style folder.

Questions:
Answers:

I hope this is what you are looking for, but I have done this a couple times where I liked a rounded button a little bit more, or if it’s a widget, I wanted a checkbox. Here’s a couple examples I just did by just changing android:background:

 <Button
            android:id="@+id/widget_yes_no_checkbox_off"
            android:layout_width="@dimen/checkbox_size"
            android:layout_height="@dimen/checkbox_size"
            android:layout_marginEnd="@dimen/right_margin"
            android:layout_gravity="center"
            android:background="@android:drawable/checkbox_off_background"
           />

This gave me a button that looks like a checkbox (necessary for making a checkbox in a widget).

Or, here’s a drawable xml to help me round a button

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="@color/primaryDarkColor"/>
    <corners android:radius="20dp"/>
</shape>

with it’s corresponding style theme:

 <style name="myAppStyle.ButtonStyle">
        <item name="android:background">@drawable/rounded_button</item>
    </style>

So, in summary, I think the easiest way to do this is to still do a button layout, but use the background attribute to change the way your button looks.