如何在android studio中缩放不同屏幕尺寸的自定义按钮?

时间:2017-06-15 17:15:44

标签: android xml

我使用以下xml文件创建了一个自定义按钮drawable:

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>

我喜欢这样,因为我使用这样的代码将这个drawable应用于按钮:

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

然而,我的问题出现在使用标签上。当然,这会导致按钮在不同屏幕上的大小相同。有没有办法让我可以缩放这个drawable,以便在不同的屏幕上有不同的尺寸?

1 个答案:

答案 0 :(得分:0)

我知道最简单的方法是为不同的屏幕尺寸创建多个xml文件。

要做到这一点,

res文件夹中右键单击drawable文件夹。

转到新的 - &gt;可绘制资源文件enter image description here

它应该显示一个表单:

将名称设置为与其他名称完全相同

但添加一个quailifer:

enter image description here

这将为该特定大小创建一个新的文件夹和xml文件。

enter image description here

对这些文件夹中的每个xml文件进行更改以获得正确的缩放

编辑:

Here

找到

enter image description here