Custom Control---Inherit view class mode (custom switch effect case)

Source: Internet
Author: User

----------------------------------------------------a simple------------------------------------------------------------------ --------



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.atguigu.mytogglebutton.mytoggleview        android:layout_width=" Wrap_content "        android:layout_height= "Wrap_content"        android:layout_centerinparent= "true"        /></relativelayout>

Mainactivity.java

Package Com.atguigu.mytogglebutton;import Android.os.bundle;import Android.app.activity;import android.view.Menu; public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);}}
Mytoggleview.java

Package Com.atguigu.mytogglebutton;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.util.attributeset;import Android.view.motionevent;import Android.view.View /** * Set Slide effect * 1, Finger press Record coordinates * 2, come to new coordinate record * 3, calculate offset * 4, move button according to offset * 5, block illegal value * 6, Reinitialize initial value */public class Mytoggleview ext Ends View implements View.onclicklistener {//true: On state false: off state (default off state) Private Boolean isopened = false;//Brush-Accessibility Priv Ate Paint paint;//background image private Bitmap backgroudbitmap;private Bitmap slidingbitmap;//slide button distance to left private float sledingleft;//Slide button The maximum distance from the left private float maxleft;/** * Custom control construction Method-with style */public Mytoggleview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); Initview ();} /** * System stipulates that the layout file using view, when instantiated only with two parameters of the construction method */public Mytoggleview (context context, AttributeSet Attrs) {Super (context, ATTRS); Initview ();} /*** Usually use */public Mytoggleview (context context) {Super (context) when instantiating in Code, Initview ();} /** * Initialize view */private void Initview () {//create brush paint = new paint ();//Set anti-aliasing Paint.setantialias (true);//create background picture backgroudbit Map = Bitmapfactory.decoderesource (Getresources (), r.drawable.switch_background); Slidingbitmap = Bitmapfactory.decoderesource (Getresources (), R.drawable.slide_button);//The maximum distance from the left of the sliding button Maxleft = Backgroudbitmap.getwidth ()-slidingbitmap.getwidth ();//Set Click event MyToggleView.this.setOnClickListener (this);} /** * Main methods of execution: * 1. Construction * 2. Measuring-onmeasure (); Usually the time of the view is measured * 3. Specify the size and position of the view: OnLayout (); * General view is not available, but if the current view inherits ViewGroup, be sure to implement it and be obligated to specify the child's location and size. * 4. Draw-ondraw (); * 5, Ontouchevent () *//** * 1.View the size of itself, which is determined by onmeasure (); * 2.View position in ViewGroup, this is determined by onlayout () * 3. Draw View,ondraw () Defines how to draw this view */@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {// Specify Size setmeasureddimension (Backgroudbitmap.getwidth (), Backgroudbitmap.getheight ());} /** * * * draw */@Overrideprotected void OndraW (canvas canvas) {////Canvas.drawbitmap (bitmap, left, top, paint) Top (draw from top left vertex) canvas.drawbitmap (backgroudbitmap, 0, 0, paint); Canvas.drawbitmap (Slidingbitmap, sledingleft, 0, paint);} The coordinate of the starting x-axis private float startx;//history X-axis coordinates private float lastx;/** * True: Click event Effective Touch event does not take effect false: Click event does not take effect, touch event takes effect */private bo Olean Isclickenbale = false;/** * Touch Event */@Overridepublic Boolean ontouchevent (Motionevent event) {super.ontouchevent ( event), switch (Event.getaction ()) {case motionevent.action_down://Press//1. The coordinates of the finger press LASTX = StartX = Event.getx ();//When the finger is pressed, Set status for click events to take effect, touch event does not take effect Isclickenbale = true;break;case motionevent.action_move://swipe//2. Come to new coordinates float NEWX = Event.getx (); /3. Calculate offset Float Distancex = newx-startx;//distance from start to now if (Math.Abs (NEWX-LASTX) > 5) {//If the offset is greater than 5, the set state is invalid for the Click event, the touch event takes effect is Clickenbale = false;} Redraw interface Flunshview (DISTANCEX);//5. Re-record the initial value startx = Event.getx (); Break;case motionevent.action_up://leave//If the touch event takes effect, Click event Expiration if (!isclickenbale) {//If the distance from the left side of the slide button is greater than half the maximum distance from the left of the slide button, set the state to open if (sledingleft > maxleft/2) {isopened = true;} else if (Sledingleft <= maxleft/2) {//If the distance to the left of the slide button is less than half the maximum distance from the left of the slide button, set the state to Off is Opened = false;} Redraw interface Flushviewstate ();} Break;default:break;} return true;} /** * block illegal values and redraw */private void Flunshview (float Distancex) {sledingleft + = distancex;if (Sledingleft < 0) According to location {sleding left = 0;} if (Sledingleft > Maxleft) {sledingleft = Maxleft;} 4. Draw invalidate () according to the latest position; /** * Click event */@Overridepublic void OnClick (View v) {//If the click State is in effect, the touch event expires if (Isclickenbale) {flushviewstate ();//Click, if the status is on Then set to OFF, if it is off the state is set to open isopened =!isopened;}} private void Flushviewstate () {//Open state if (isopened) {//Open state sledingleft = Maxleft;} else {//off state sledingleft = 0;} Invalidate ();//execution in the main thread causes OnDraw to execute}}



Custom Control---Inherit view class mode (custom switch effect case)

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.