Android slide switch-ToggleButton (source code)

Source: Internet
Author: User
Tags gety

Let's take a look at the sliding switch:

Let's start with the code:

Here is the custom control ToggleButton. java:

package com.fay.toggle;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.util.AttributeSet;import android.util.Log;import android.view.MotionEvent;import android.view.View;/** * toggle the status * @since 2014/05/22 * @author Fay * {@link 1940125001@qq.com} */public class ToggleButton extends View {    private String TAG = "ToggleButton";        //the bitmap of toggle on    private Bitmap backgroudBitmap = null;        //the bitmap of toggle flip    private Bitmap slidingBitmap = null;        //whether is button if is Sliding    private boolean isSliding = false;        //the previous state of the button    private boolean previousState = false;        private Paint mPaint = new Paint();        private Matrix mMatrix = new Matrix();        private OnToggleStateChangedListener mOnToggleStateChangedListener = null;        //current X-Location which touched    private float touchXLocation = 0;        //the slidingBitmap inner margin the  ToggleButton    private float marginLeft = 0;            public ToggleButton(Context context) {        super(context);    }    public ToggleButton(Context context, AttributeSet attrs) {        super(context, attrs);    }    public ToggleButton(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }        /**     * set the background for the ToggleButton and sliding image resource     * @param int backgroudResID     * @param int flipResID     */    public void setImageResource(int backgroudResID, int flipResID) {        backgroudBitmap = BitmapFactory.decodeResource(getResources(), backgroudResID);        slidingBitmap = BitmapFactory.decodeResource(getResources(), flipResID);    }        /**     * set the initialize state of the view     * @param boolean isOn     */    public void setInitState(boolean isOn) {                                                                                                                                                                                                                      previousState = isOn;    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        // TODO Auto-generated method stub        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }    @Override    protected void onDraw(Canvas canvas) {        canvas.drawBitmap(backgroudBitmap, mMatrix, mPaint);        if (isSliding) {//if sliding            //to avoid slidingBitmap sliding out of the ToggleButton            if (touchXLocation >= backgroudBitmap.getWidth() - slidingBitmap.getWidth() /2                     || touchXLocation <=  slidingBitmap.getWidth() /2) {                                if (touchXLocation >= backgroudBitmap.getWidth() - slidingBitmap.getWidth() /2) {                    marginLeft = backgroudBitmap.getWidth() - slidingBitmap.getWidth();                } else  {                    marginLeft = 0;                }            } else {                marginLeft = touchXLocation - slidingBitmap.getWidth() / 2;            }            canvas.drawBitmap(slidingBitmap, marginLeft, 0, mPaint);        } else {            if (previousState == true) {//on                canvas.drawBitmap(slidingBitmap, backgroudBitmap.getWidth() - slidingBitmap.getWidth(), 0, mPaint);            } else {                canvas.drawBitmap(slidingBitmap, 0, 0, mPaint);            }        }        super.onDraw(canvas);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        switch (event.getAction()) {        case MotionEvent.ACTION_DOWN:            if (0 <= event.getX() && event.getX() <= backgroudBitmap.getWidth()                         && 0 <= event.getY() && event.getY() <= backgroudBitmap.getHeight() ) {                touchXLocation = event.getX();                isSliding = true;            } else {                isSliding = false;            }            break;        case MotionEvent.ACTION_MOVE:            if (isSliding) {//to avoid change the state out of the toggle                touchXLocation = event.getX();            }            break;        case MotionEvent.ACTION_UP:            isSliding = false;            if (touchXLocation > backgroudBitmap.getWidth() / 2) {//on                //if previous state is off                if (previousState == false) {                    mOnToggleStateChangedListener.changed(true);                    previousState = true;                }            } else if (touchXLocation <  backgroudBitmap.getWidth() / 2) {//off                //if previous state if on                if (previousState == true) {                    mOnToggleStateChangedListener.changed(false);                    previousState = false;                }            }            break;        }        invalidate();        return true;    }        /**     * The Listener of this ToggleButton     */    public interface OnToggleStateChangedListener {        void changed(boolean isOn);    }        /**     * set the Listener for the ToggleButton     */    public void setOnStateChangedListener(OnToggleStateChangedListener mOnToggleStateChangedListener) {        this.mOnToggleStateChangedListener = mOnToggleStateChangedListener;    }}


Then let's take a look at the activity layout activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <com.fay.toggle.ToggleButton        android:id="@+id/toggle"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="50dp"        android:layout_marginRight="50dp" >    </com.fay.toggle.ToggleButton></RelativeLayout>

Then we use MainActivity. java for this control.

package com.fay.toggle;import android.app.Activity;import android.os.Bundle;import android.widget.Toast;import com.fay.toggle.ToggleButton.OnToggleStateChangedListener;public class MainActivity extends Activity {    private ToggleButton mToggleButton = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mToggleButton = (ToggleButton) findViewById(R.id.toggle);        mToggleButton.setInitState(false);        mToggleButton.setImageResource(R.drawable.bkg_switch, R.drawable.btn_slip);        mToggleButton.setOnStateChangedListener(new OnToggleStateChangedListener() {            @Override            public void changed(boolean isOn) {                Toast.makeText(getApplicationContext(), isOn + "", 2000).show();            }        });    }}


As you can see, in MainActivity. the use of ToggleButton in java is very simple and convenient. this control integrates the View and overwrites the onDraw () method in it for plotting. and set the listener. because the usage is very simple, I don't need to worry about it. I hope you will give me some valuable suggestions in time!

Download link: http://files.cnblogs.com/yinweiliang/ToggleButton.rar

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.