嗯~ 仅做片段速记。
更改 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
=========================================================================