一手遮天 Android - view(选择类): ToggleButton 样式
示例如下:
/view/selection/ToggleButtonDemo2.java
/**
* ToggleButton - 双状态按钮
* setButtonDrawable() - 设置双状态按钮在各种状态下的样式
*/
package com.webabcd.androiddemo.view.selection;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ToggleButton;
import com.webabcd.androiddemo.R;
public class ToggleButtonDemo2 extends AppCompatActivity {
private ToggleButton _toggleButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_selection_togglebuttondemo2);
_toggleButton2 = (ToggleButton)findViewById(R.id.toggleButton2);
_toggleButton2.setButtonDrawable(R.drawable.selector_togglebutton_button);
}
}
/layout/activity_view_selection_togglebuttondemo2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--
ToggleButton - 双状态按钮
setButtonDrawable() - 设置双状态按钮在各种状态下的样式(参见 drawable/selector_togglebutton_button.xml)
-->
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="32dp"
android:layout_height="32dp"
android:button="@drawable/selector_togglebutton_button"
android:textOff="@null"
android:textOn="@null"/>
<!--
在 java 中设置 ToggleButton 的 button
-->
<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="关"
android:textOn="开"/>
</LinearLayout>
/drawable/selector_togglebutton_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--
state_enabled="true" - 可用
state_enabled="false" - 不可用
state_checked="true" - 选中
state_checked="false" - 未选中
注意:可以直接在 item 的 drawable 指定图片,但是这样只能按照原图的大小显示,如果需要指定图片的显示大小的话,则需要像本例这样使用 layer-list
-->
<item
android:state_enabled="true"
android:state_checked="true"
android:drawable="@drawable/layerlist_togglebutton_button_checked" />
<item
android:state_enabled="true"
android:state_checked="false"
android:drawable="@drawable/layerlist_togglebutton_button_unchecked" />
</selector>