网上找了好久,发现switchbutton许多都是自定义的,或者比较麻烦,所以自己在网上找了一种很好用的switchbutton,简单方便,可以做按钮监听并且可以自己定义按钮的颜色
(1)在builder.gradle中引用第三方的类库:
compile 'com.github.zcweng:switch-button:[email protected]'
(2)在xml中可以直接使用switchbutton控件,并且有多种颜色和效果选择:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:background="#fff" android:orientation="vertical" android:padding="20dp"> <com.suke.widget.SwitchButton android:id="@+id/switch_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp"/> <com.suke.widget.SwitchButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:sb_checked="true"/> <com.suke.widget.SwitchButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:sb_show_indicator="false" app:sb_checked="true"/> <com.suke.widget.SwitchButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:sb_checked_color="#fdc951" app:sb_checked="true"/> <com.suke.widget.SwitchButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:sb_button_color="#db99c7" app:sb_shadow_color="#A36F95" app:sb_background="#FFF" app:sb_checkline_color="#a5dc88" app:sb_checked_color="#A36F95" app:sb_uncheckcircle_color="#A36F95" /> <com.suke.widget.SwitchButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:sb_enable_effect="false"/> </LinearLayout>
(3)如果你只想要效果,不需要做操作的话,到这里就结束了,直接导入布局就可以看到效果。但是在做开发的时候,做这个一个按钮出来不可能是没有作用的,所以我们需要加一个监听
switch_button = (SwitchButton)findViewById(R.id.switch_button); switch_button.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(SwitchButton view, boolean isChecked) { if (isChecked){ Log.e("TAG","按钮打开"); }else{ Log.e("TAG","按钮关闭"); } } });
(4)运行效果图: