JD Sal
JD Sal

Reputation: 5

How to scale a custom button drawable for different screen sizes in android studio?

I have created a custom button drawable using the following xml files:

button.xml

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/button_pressed" />
    <item
        android:state_enabled="true"
        android:drawable="@drawable/button_enabled"/>
</selector>

button_pressed.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <size
        android:width="70dp"
        android:height="70dp"/>
    <gradient
        android:startColor="#000000"
        android:centerColor="#000000"
        android:endColor="#000000"
        android:angle="90"/>
    <padding android:left="3dp"
        android:top="3dp"
        android:right="3dp"
        android:bottom="3dp" />
    <stroke
        android:width="3dp"
        android:color="#05B402" />
</shape>

button_enabled.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <size
        android:width="70dp"
        android:height="70dp" />
    <gradient
        android:startColor="#FFFFFF"
        android:centerColor="#FFFFFF"
        android:endColor="#FFFFFF"
        android:angle="90"/>
    <padding android:left="3dp"
        android:top="3dp"
        android:right="3dp"
        android:bottom="3dp" />
    <stroke
        android:width="3dp"
        android:color="#05B402" />
</shape>

I have it like this because I apply this drawable to buttons using code like this:

Button b = new Button(getActivity());
b.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.button));

However, my problem arises in using the tag. Naturally, this causes the button to be the same size across different screens. Is there a way so that I can scale this drawable so that it is a different size on different screens?

Upvotes: 0

Views: 746

Answers (1)

Tony
Tony

Reputation: 3068

The easiest way I know, is to create multiple xml files for the different screen sizes.

To do this,

in your res folder right click drawable folder.

goto new -> Drawable resource fileenter image description here

it should show a form:

set the name as the exact same as the others

but add a quailifer:

enter image description here

this will create a new folder and xml file for that specific size.

enter image description here

Make the changes to each xml file in those folders to get the correct scaling

EDIT:

Found from Here

enter image description here

Upvotes: 1

Related Questions