【android开发】滑动按钮 SlipSwitch开关的实现

来源:互联网 发布:安全狗防sql注入 编辑:程序博客网 时间:2024/05/05 21:21

       项目新加入一个网络模式选择的功能,要求实现一个类似于开关的效果,在网上查了查了一些资料,看到有很多例子,大家完全可以拿来用,当然了,自己掌握了才是自己的东西,现在把我用的分享给大家,希望能帮助一些朋友!下面上图,看一下效果:


其实这个开关实现起来确实很简单,下面把一下代码贴出来:

准备两张图片

    

这两张图,下载可以直接使用。

新建一个MySlipSwitch类:

------------------------------------------------------------------------------------

package com.tp.insurance.util;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Matrix;import android.graphics.Paint;import android.graphics.Rect;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;/** * 类名称:MySlipSwitch  * 类描述:设置中的网络连接功能手动模式自定义开关 * 创建人:LiXinhui  * 创建时间:2013-10-16 上午10:20:00  */public class MySlipSwitch extends View implements OnTouchListener{//开关开启时的背景,关闭时的背景,滑动按钮private Bitmap switch_on_Bkg, switch_off_Bkg, slip_Btn;private Rect on_Rect, off_Rect;//是否正在滑动private boolean isSlipping = false;//当前开关状态,true为开启,false为关闭private boolean isSwitchOn = false;//手指按下时的水平坐标X,当前的水平坐标Xprivate float previousX, currentX;//开关监听器private OnSwitchListener onSwitchListener;//是否设置了开关监听器private boolean isSwitchListenerOn = false;public MySlipSwitch(Context context) {super(context);init();}public MySlipSwitch(Context context, AttributeSet attrs) {super(context, attrs);init();}private void init() {setOnTouchListener(this);}public void setImageResource(int switchOnBkg, int switchOffBkg, int slipBtn) {switch_on_Bkg = BitmapFactory.decodeResource(getResources(), switchOnBkg);switch_off_Bkg = BitmapFactory.decodeResource(getResources(), switchOffBkg);slip_Btn = BitmapFactory.decodeResource(getResources(), slipBtn);//右半边Rect,即滑动按钮在右半边时表示开关开启on_Rect = new Rect(switch_off_Bkg.getWidth() - slip_Btn.getWidth(), 0, switch_off_Bkg.getWidth(), slip_Btn.getHeight());//左半边Rect,即滑动按钮在左半边时表示开关关闭off_Rect = new Rect(0, 0, slip_Btn.getWidth(), slip_Btn.getHeight());}public void setSwitchState(boolean switchState) {isSwitchOn = switchState;}protected boolean getSwitchState() {return isSwitchOn;}protected void updateSwitchState(boolean switchState) {isSwitchOn = switchState;invalidate();}@Overrideprotected void onDraw(Canvas canvas) {// TODO Auto-generated method stubsuper.onDraw(canvas);Matrix matrix = new Matrix();Paint paint = new Paint();//滑动按钮的左边坐标float left_SlipBtn;//手指滑动到左半边的时候表示开关为关闭状态,滑动到右半边的时候表示开关为开启状态if(currentX < (switch_on_Bkg.getWidth() / 2)) {canvas.drawBitmap(switch_off_Bkg, matrix, paint);} else {canvas.drawBitmap(switch_on_Bkg, matrix, paint);}//判断当前是否正在滑动if(isSlipping) {if(currentX > switch_on_Bkg.getWidth()) {left_SlipBtn = switch_on_Bkg.getWidth() - slip_Btn.getWidth();} else {left_SlipBtn = currentX - slip_Btn.getWidth() / 2;}} else {//根据当前的开关状态设置滑动按钮的位置if(isSwitchOn) {left_SlipBtn = on_Rect.left;} else {left_SlipBtn = off_Rect.left;}}//对滑动按钮的位置进行异常判断if(left_SlipBtn < 0) {left_SlipBtn = 0;} else if(left_SlipBtn > switch_on_Bkg.getWidth() - slip_Btn.getWidth()) {left_SlipBtn = switch_on_Bkg.getWidth() - slip_Btn.getWidth();}canvas.drawBitmap(slip_Btn, left_SlipBtn, 0, paint);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {// TODO Auto-generated method stubsetMeasuredDimension(switch_on_Bkg.getWidth(), switch_on_Bkg.getHeight());}@Overridepublic boolean onTouch(View v, MotionEvent event) {// TODO Auto-generated method stubswitch(event.getAction()) {//滑动case MotionEvent.ACTION_MOVE:currentX = event.getX();break; //按下case MotionEvent.ACTION_DOWN:if(event.getX() > switch_on_Bkg.getWidth() || event.getY() > switch_on_Bkg.getHeight()) {return false;} isSlipping = true;previousX = event.getX();currentX = previousX;break;//松开case MotionEvent.ACTION_UP:isSlipping = false;//松开前开关的状态boolean previousSwitchState  = isSwitchOn;if(event.getX() >= (switch_on_Bkg.getWidth() / 2)) {isSwitchOn = true;} else {isSwitchOn = false;}//如果设置了监听器,则调用此方法if(isSwitchListenerOn && (previousSwitchState != isSwitchOn)) {onSwitchListener.onSwitched(isSwitchOn);}break;default:break;}//重新绘制控件invalidate();return true;}public void setOnSwitchListener(OnSwitchListener listener) {onSwitchListener = listener;isSwitchListenerOn = true;}public interface OnSwitchListener {abstract void onSwitched(boolean isSwitchOn);}}

-------------------------------------------------------------------------------------

然后在一个布局文件中添加一个控件select_network.xml:

-------------------------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@drawable/viewbackground"    android:orientation="vertical" >    <include        android:id="@+id/settings_modify_pwd"        layout="@layout/title_normal1" />    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"         android:layout_marginTop="100dp"        android:orientation="vertical">        <LinearLayout            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:layout_gravity="center_horizontal"            android:background="@drawable/username_background"            android:gravity="center_vertical"            android:orientation="horizontal" >            <ImageView                android:layout_width="0px"                android:layout_weight="1"                android:layout_height="wrap_content"                android:layout_marginLeft="20dp"                android:background="@drawable/hand_movement" />            <TextView                android:layout_width="0px"                android:layout_weight="4"                android:layout_height="wrap_content"                android:text="手动模式"                android:layout_marginLeft="10dp"                android:textColor="#000000"                android:textSize="21dp" />          <View       android:layout_width="1dip"       android:layout_height="match_parent"       android:layout_marginLeft="20dp"       android:background="#ff00ff66" />           <com.tp.insurance.util.MySlipSwitch  android:id="@+id/mss_select_network"  android:layout_width="0px"  android:layout_weight="4"  android:layout_height="wrap_content"  android:layout_marginLeft="40dp"  android:layout_marginRight="5dp" />        </LinearLayout>        <LinearLayout            android:id="@+id/ll_apn"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:layout_gravity="center_horizontal"            android:background="@drawable/password_background"            android:gravity="center_vertical"            android:orientation="horizontal" >       <RadioGroup           android:id="@+id/rg_select_network"            android:layout_width="wrap_content"           android:layout_height="wrap_content"           android:orientation="vertical"           android:layout_marginLeft="15dp">           <RadioButton               android:id="@+id/rb_outnet"                android:layout_width="wrap_content"               android:layout_height="wrap_content"               android:text="外网连接"               android:textSize="20dp"               />           <RadioButton               android:id="@+id/rb_apn"                android:layout_width="wrap_content"               android:layout_height="wrap_content"               android:text="APN连接"               android:textSize="20dp"               />       </RadioGroup>        </LinearLayout>    </LinearLayout></RelativeLayout>

------------------------------------------------------------------------------------

最后在activity中绑定、监听就行,和使用其他的控件的操作基本就一样了SelectNetworkActivity.java:

注意,我的这个activity是通过其他activity调用的。

--------------------------------------------------------------------------------------

package com.tp.insurance.ui;import com.tp.insurance.R;import com.tp.insurance.util.MySlipSwitch;import com.tp.insurance.util.MySlipSwitch.OnSwitchListener;import com.tp.insurance.util.Util;import android.annotation.SuppressLint;import android.app.Activity;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageView;import android.widget.RadioButton;import android.widget.RadioGroup;import android.widget.RadioGroup.OnCheckedChangeListener;import android.widget.Toast;/** * 类名称:SelectNetworkActivity  * 类描述:设置中的网络连接功能 * 创建人:LiXinhui  * 创建时间:2013-10-16 上午10:30:00  */public class SelectNetworkActivity extends Activity implements OnCheckedChangeListener{private ImageView title_back;//返回上一级private MySlipSwitch slipswitch_MSL;//自定义开关private RadioGroup isOpenWLAN;private RadioButton rbOpenOutNet;private RadioButton rbOpenAPN;private SharedPreferences sharedPreferences;private int isManual;//存放模式,0为自动模式,1为手动模式private int selectNetWork;//存放网络方式,0为外网连接,1为APN连接private Editor editor;@SuppressLint("ShowToast")@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.select_network);initView();        slipswitch_MSL.setOnSwitchListener(new OnSwitchListener() {@Overridepublic void onSwitched(boolean isSwitchOn) {// TODO Auto-generated method stubif(isSwitchOn) {editor.putInt("isManual", 1);editor.commit(); // 提交数据, 保存到文件if(selectNetWork == 0){rbOpenOutNet.setChecked(true);}else{rbOpenAPN.setChecked(true);}rbOpenOutNet.setEnabled(true);rbOpenAPN.setEnabled(true);Toast.makeText(SelectNetworkActivity.this, "手动模式", 300).show();} else {editor.putInt("isManual", 0);editor.commit(); // 提交数据, 保存到文件rbOpenOutNet.setEnabled(false);rbOpenAPN.setEnabled(false);Toast.makeText(SelectNetworkActivity.this, "自动模式", 300).show();}}});}@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {// TODO Auto-generated method stubint getRadioButtonID = group.getCheckedRadioButtonId();if(getRadioButtonID == R.id.rb_outnet){editor.putInt("selectNetWork", 0);//0是OutNet,1是APNeditor.commit();}else{editor.putInt("selectNetWork", 1);//0是OutNet,1是APNeditor.commit();}}//初始化UIprivate void initView(){//绑定相关控件的IDtitle_back = (ImageView) findViewById(R.id.title_backBtn);isOpenWLAN = (RadioGroup) findViewById(R.id.rg_select_network);rbOpenOutNet = (RadioButton) findViewById(R.id.rb_outnet);rbOpenAPN = (RadioButton) findViewById(R.id.rb_apn);isOpenWLAN.setOnCheckedChangeListener(this);slipswitch_MSL = (MySlipSwitch)findViewById(R.id.mss_select_network);//数据保存到sharedPreferences文件中sharedPreferences = getSharedPreferences("isManual",MODE_PRIVATE);editor = sharedPreferences.edit();isManual = sharedPreferences.getInt("isManual", 0);selectNetWork = sharedPreferences.getInt("selectNetWork", 0);        slipswitch_MSL.setImageResource(R.drawable.bkg_switch, R.drawable.bkg_switch, R.drawable.btn_slip);        if(isManual == 0){        slipswitch_MSL.setSwitchState(false);//开关为关闭状态        rbOpenOutNet.setEnabled(false);rbOpenAPN.setEnabled(false);        }else{        slipswitch_MSL.setSwitchState(true);//开关为开启状态        if(selectNetWork == 0){rbOpenOutNet.setChecked(true);}else{rbOpenAPN.setChecked(true);}        }        title_back.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {finish();}});}}

-------------------------------------------------------------------------------------

主要实现过程就是上面的了,大家可以根据自己的需要,进行修改,已达到符合自己项目的要求呀!

原创粉丝点击