ToggleButton和Switch

状态开关ToggleButton与开关switch也是由button按钮派生出来的,因此他们的本质也是按钮,button支持的各种属性,方法toggleButton和switch也适用。

ToggleButton常用的属性:

android:textOff:按钮关闭时显示的文本;
android:textOn:按钮开启时显示的文本;

Switch也用于开关按钮。Switch和ToggleButton稍有区别:ToggleButton是按下弹起的开关,而Switch是左右滑动的开关。

开关监听为:setOnCheckedChangeListener,覆写onCheckedChanged(CompoundButton buttonView, boolean isChecked)方法,其中isChecked表示是否选中。

layout文件

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ToggleButton        android:id="@+id/tbtn_open"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textOn="开"        android:textOff="关"        android:checked="true"/>    <Switch        android:id="@+id/sw"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/tbtn_open"        android:layout_marginTop="20dp"        android:checked="true"/>RelativeLayout>

Activity

public class ToggleButtonActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{    private ToggleButton mBtnopen;    private Switch mBtnsw;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_toggle_button);        mBtnopen = findViewById(R.id.tbtn_open);        mBtnsw = findViewById(R.id.sw);        mBtnopen.setOnCheckedChangeListener(this);        mBtnsw.setOnCheckedChangeListener(this);    }    @Override    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {        switch (compoundButton.getId()){            case R.id.tbtn_open:                if(compoundButton.isChecked()) Toast.makeText(this,"开",Toast.LENGTH_SHORT).show();                else Toast.makeText(this,"关",Toast.LENGTH_SHORT).show();                break;            case R.id.sw:                if(compoundButton.isChecked()) Toast.makeText(this,"开关:ON",Toast.LENGTH_SHORT).show();                else Toast.makeText(this,"开关:OFF",Toast.LENGTH_SHORT).show();                break;        }    }}

效果图

    

 

     

 

更多相关文章

  1. Android(安卓)自定义View基本用法
  2. Android(安卓)自定义实现switch开关按钮
  3. Android中使用BottomNavigationBar实现仿微信底部按钮
  4. Android开发实践 Intent 解析
  5. android:shape妙用
  6. Android使用Intent返回上一个Activity时StackOverflowError
  7. 【Android】TabLayout 自定义指示器 Indicator 样式
  8. Android(安卓)状态栏下拉列表添加自定义item开关
  9. Android(安卓)System Property

随机推荐

  1. Android(安卓)控件view的可见,不可见,隐
  2. Android(安卓)Gesture 手势识别使用实例
  3. 老罗Android开发视频教程 (android解析xml
  4. Android(安卓)常用开发工具以及Mac常用软
  5. android:screenorientation
  6. Android(安卓)Notes
  7. android应用自定义字体
  8. Android(安卓)布局各个属性的含义
  9. Android架构组件-Lifecycle
  10. TextView之二:常用属性