android - 更改切换按钮的颜色
解决方案
ToggleButton Btn=new ToggleButton(this);// or get it from the layout by ToggleButton Btn=(ToggleButton) findViewById(R.id.IDofButton);
Btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked)
buttonView.setBackgroundColor(Color.GREEN);
else buttonView.setBackgroundColor(Color.RED);
}
});
在 drawable 文件夹中,创建一个 xml 文件 my_btn_toggle.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@color/red" />
<item android:state_checked="true" android:drawable="@color/green" />
</selector>
并在 xml 部分定义您的切换按钮:
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="@+id/toggleButton"
android:background="@drawable/my_btn_toggle"/>
最后但并非最不重要的 :)
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_selected" android:state_checked="true" android:state_pressed="true"/>
<item android:drawable="@drawable/bg_selected" android:state_checked="true" android:state_focused="false"/>
<item android:drawable="@drawable/bg_normal" android:state_checked="false" android:state_pressed="true"/>
<item android:drawable="@drawable/bg_normal" android:state_checked="false" android:state_focused="false"/>
推荐阅读
- python-3.x - 将输入存储为变量然后尝试使用正则表达式提取为字符串会给出错误:AttributeError: 'str' object has no attribute 'str'
- javascript - 在多个 html 文件上使用 innerHTML/innerText 打印变量
- java - 如何在informix中从另一个数据库复制表ddl和数据
- flutter - 为什么函数在 Flutter 中返回一个空列表
- android - 在 EditText.addTextChangedListener() 中引用字符串字段值的最佳方法是什么?
- node.js - 将 mongoDB 游标转换为 JSON
- java - 如何将 RestController 更改为 MVC 控制器?
- python - 从远程计算机python获取当前日期时间
- c++ - c++ Boost : gregorian_calendar.ipp(77,1): error C2666: '-': 17 重载在 Visual Studio 2019 x64 中有类似的转换
- html - 我无法使用 :cue 等将 CSS 正确应用于字幕