【Android开发--新手必看篇】Switch 开关(含自定义样式)

    技术2022-08-01  101

    Android笔记

    ​ ——各类控件的使用(控件)-开关 【若对该知识点有更多想了解的,欢迎私信博主~~】

    开关:Switch

    属性:
    XML属性说明layout_width布局宽度layout_height布局高度switchMinWidth设置开关的最小宽度textOn按钮被选中时显示的文字textOff按钮没有被选中时显示的文字checked是否被选中track开关轨道的颜色thumb开关按钮的颜色showText设置on/off的时候是否显示文字splitTrack是否设置一个间隙,让滑块与底部图片分隔
    注:textOn和textOff使用时showText必须为true
    方法:
    常用方法说明isChecked()被选中
    高级方法:当前状态更改时触发
    Switch aSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main26); //绑定控件 aSwitch = findViewById(R.id.switch1); //当前状态更改时触发 aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { Toast.makeText(Main26Activity.this, "被改变了", Toast.LENGTH_SHORT).show(); } }); }
    高级样式:按钮与轨道的样式改变

    按钮(此文件名thumb)

    <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true"> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!--高度40--> <size android:width="40dp" android:height="40dp" /> <!--圆角弧度20--> <corners android:radius="20dp" /> <!--变化率--> <gradient android:endColor="#eeeeee" android:startColor="#eeeeee" /> <stroke android:width="1dp" android:color="#33da33" /> </shape> </item> <item android:state_checked="false"> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <!--高度40--> <size android:height="40dp" android:width="40dp" /> <!--圆角弧度20--> <corners android:radius="20dp"/> <!--变化率--> <gradient android:endColor="#eeeeee" android:startColor="#eeeeee" /> <stroke android:width="1dp" android:color="#666666" /> </shape> </item> </selector>

    轨道(此文件名track)

    <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true"> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <!--高度30此处设置宽度无效--> <size android:height="40dp"/> <!--圆角弧度15--> <corners android:radius="15dp"/> <!--变化率--> <gradient android:endColor="#33da33" android:startColor="#33da33"/> </shape> </item> <item android:state_checked="false"> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <!--高度30此处设置宽度无效--> <size android:height="40dp"/> <!--圆角弧度15--> <corners android:radius="15dp"/> <!--变化率定义从左到右的颜色不变--> <gradient android:endColor="#888888" android:startColor="#888888"/> </shape> </item> </selector>

    使用(XML样式文件中)

    <Switch android:id="@+id/switch1" android:layout_width="110dp" android:layout_height="160dp" android:checked="true" android:showText="true" android:splitTrack="true" android:switchMinWidth="110dp" android:textOff="off" android:textOn="on" android:thumb="@drawable/thumb" android:track="@drawable/track" />
    Processed: 0.008, SQL: 10