Android滑動開關-ToggleButton(附源碼)

來源:互聯網
上載者:User

我們先看下滑動開關的:

我們先上代碼:

這裡是自訂控制項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;    }}


然後我們看下這個活動的布局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>

然後我們這個活動對這個控制項的使用MainActivity.java

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


各位朋友可以看到,在MainActivity.java中對ToggleButton的使用是十分簡單方便.這個控制項通過整合View,重寫裡面的onDraw()方法進行繪圖.以及設定監聽器.由於用法十分簡單,我就不需要囉嗦了.其中有不妥之處,希望各位道友及時給我您寶貴的建議!

下載連結:http://files.cnblogs.com/yinweiliang/ToggleButton.rar

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.