在 Android 上自定义切换按钮 [英] customize toggle button on Android

查看:46
本文介绍了在 Android 上自定义切换按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用选择器定义的可绘制对象自定义了切换按钮.我使用这个 drawable 作为切换按钮的背景.

I customized the Toggle button by using a drawable defined by using a selector. I use this drawable as background for the Toggle button.

<ToggleButton
    android:id="@+id/mailbox:toggle_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_weight="1"
    android:background="@drawable/toggle_background"
    android:gravity="center_horizontal|center_vertical" />

toggle_background 在此处定义:

The toggle_background is defined here:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:drawable="@drawable/img1"
            android:state_checked="true" />
        <item
            android:drawable="@drawable/img2"
            android:state_checked="false" />    
    </selector>

问题是图像总是被拉伸.有没有办法为两个未拉伸的状态定义图像?

The problem is that the image is always stretched. Is there a way to define an image for the two states that is not stretched?

我需要的是一个会被拉伸的背景,以及一个不能被拉伸的图标在按钮的中心.

What I need is a background that will be stretched and in the center of the button an icon that must not be stretched.

有可能吗?

推荐答案

我也是这样做的,按钮:

I did the same task this way, the button:

        <ToggleButton  android:id="@+id/mlAbout"
            android:textOn="@string/about"
            android:textOff="@string/about"
            android:background="@drawable/ml_about" />

@drawable/ml_about:

@drawable/ml_about:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/list_bg_top"></item>
    <item android:left="10dp">
        <bitmap android:src="@drawable/waiting_status_btn"
          android:gravity="center_vertical|left" />
    </item>
</layer-list>

@drawable/list_bg_top 背景图片将被拉伸,@drawable/waiting_status_btn 是不会随小部件拉伸的图标

@drawable/list_bg_top background image that will be stretched and @drawable/waiting_status_btn is the icon the will not be stretched with the widget

这篇关于在 Android 上自定义切换按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆