我的Android学习速记 (1) 更改 ToggleButton 的 背景

嗯~ 仅做片段速记。

更改 ToggleButton 的 背景

1、准备一个ToggleButton 被选中的drawable,和一个选中的drawable。

( 此处drawable可以是Drawable Resuouce xml 文件,也可以是图片文件)

我用的是图片文件 togbtn_check.png  和togbtn_uncheck.png ,它们是我复制到res/drawable里的。

   

2、在res/drawable中新建 togbtn1_backgroup.xml (togbtn1_backgroup这个名字是我随便取的)

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

3、然后在布局中将TaggleButton 的 android:backgroupd 设置为  @drawable/togbtn1_backgroup

            <ToggleButton
                android:id="@+id/mct_togbtn1"
                android:layout_width="100dp"
                android:layout_height="16dp"
                android:background="@drawable/togbtn1_backgroup"
                android:text="电机"
                android:textOff="电机"
                android:textOn="电机"/>

4、如果是在代码中更改, 要使用setBackgroundDrawable(getResources().getDrawable(R.drawable.togbtn1_backgroup)); 来设置

例:

ToggleButton togBtn1=findViewById(R.id.mct_togbtn1);
togBtn1.setBackgroundDrawable(getResources().getDrawable(R.drawable.togbtn1_backgroup));

5、值得注意的地方

        1)togbtn_check图片和大小,最好要与设计ToggleButton大小一致。否则会比较难看。

        2)如果ToggleButton要设置文字,光设置text的值是不行的,除非不要文字,text是还未选择时显示的文字  还要设置textOff与textOn的值 。

                在布局文件中使用   

        android:textOff="未选中状态下的文字"
        android:textOn="选中状态下的文字"

                在代码中使用

        togBtn1.setTextOff("未选中状态下的文字");
        togBtn1.setTextOn("选中状态下的文字");

                如果是像我现在的例子,使用图像来区分选中状态,可以把textOff与textOn的值设置成一样。

                android:text="电机"
                android:textOff="电机"
                android:textOn="电机"

      2022/02/21

=========================================================================

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值