Android ToggleButton:状态切换的Button
Android ToggleButton和Android Button类似,但是ToggleButton提供了一种选择机制,可以表达Button处于何种状态,比如常见的WiFi打开或者关闭状态等等这种类似与非门的状态机。
标准的Android ToggleButton样式简单,如果要实现自定义的、表达力丰富的ToggleButton,其中一个方式就是写selector.xml文件作为ToggleButton的background,现在写一个例子。
布局文件activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="zhangphil.demo.MainActivity">
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:checked="true"
android:textOff="关闭"
android:textOn="打开"
android:background="@drawable/selector"/>
</RelativeLayout>
activity_main.xml需要的、位于drawable目录下的selector.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/darker_gray" android:state_checked="false" />
<item android:drawable="@android:color/holo_green_light" android:state_checked="true" />
</selector>
上层Java代码:
package zhangphil.demo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton mToggleButton = (ToggleButton) findViewById(R.id.toggleButton);
mToggleButton.setOnCheckedChangeListener(mOnCheckedChangeListener);
}
private ToggleButton.OnCheckedChangeListener mOnCheckedChangeListener = new ToggleButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String s="";
if(isChecked)
s="打开";
else
s="关闭";
Toast.makeText(getApplication(),s,Toast.LENGTH_SHORT).show();
}
};
}
代码运行结果如图:
附录文章:
1,《Android Segmented RadioButton》链接地址:http://blog.csdn.net/zhangphil/article/details/51441677
2,《Android选项切换条SHSegmentControl》链接地址:http://blog.csdn.net/zhangphil/article/details/49720805