zoukankan      html  css  js  c++  java
  • Android学习03

    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;
    
            }
        }
    }

    效果图

        

         

  • 相关阅读:
    49个128*128像素的天气png图标
    非常漂亮的千千静听皮肤[Warp]出自梦梦的作品
    腾讯的面试题
    什么是函数参数,如何传递函数参数
    我看了这视频,情不自禁的笑了
    WindowBlinds基础使用教程
    晒工资网站
    一个可以搜索word文档,电子表格,PDF,幻灯片的搜索引擎
    网页设计常用png小图标一套
    使用U盘时候的”无法停用通用卷”的解决办法
  • 原文地址:https://www.cnblogs.com/xjmm/p/12257422.html
Copyright © 2011-2022 走看看