Android custom Controls--Imitation iOS switch button

Source: Internet
Author: User

Reprint Please specify source:http://blog.csdn.net/allen315410/article/details/39319057

Generally in the company to do client product development will find that the difference between Android and iOS, iOS thanks to the "Old Joe" of the careful design, user experience to achieve the ultimate interface, and Android adhering to open source ideas, user experience of the interface of the hundreds have their long, mutual not unified. Don't talk nonsense, first, look at the ios "switch button":


Often in the company, product design prototypes first refer to the design of iOS, this can be bitter for Android developers, Android developers are forced to write and iOS almost the same effect, this situation should be very common! For example, the "switch button" I mentioned below, which is integrated in iOS, is used, but does not appear in Android 4.0 after the ToggleButton components, aside from the interface (actually not very beautiful), then look at compatibility, ToggleButton is starting from 4.0 after something, then 2.3 of the system we can not ignore it, 2.3 in the market occupies a large proportion. So, to be able to do the same effect as ios "switch button", we can only "bitter" with Java code to draw out such a component.

A simple way to tell the self-drawing components, Android under the self-painting component is broadly divided into inherited view and inheritance ViewGroup two.

Implementation steps and corresponding methods:
Measure height-to-layout (placement control's position)--draw to screen
|                                                        | |
Onmeasure OnLayout OnDraw
It is important to note that if a custom component inherits ViewGroup, it must implement the above 3 steps, especially the typography, where the component display position needs to be defined. Custom components are inherited view to achieve, the layout of this step is not necessary, just complete the measurement and drawing.

The following is my Project Demo chart:

Custom "switch button" main implementation code:

Package Com.example.slidebutton.view;import Com.example.slidebutton.r;import Com.example.slidebutton.view.interf.ontogglestatechangelistener;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.util.attributeset;import Android.view.motionevent;import Android.view.view;public class SlideButton extends View {/** slide switch background */private Bitmap slidebuttonbg;/** slide block background */private Bitmap switchbg;/** set switch status, ON/off. Default: Off */private boolean currentstate = false;/** The moving distance of the current slider */private int currentx;/** record the current slide state of the slider. Default, False */private boolean issliding = false;/** switch status change monitoring */private Ontogglestatechangelistener mlistener;public Slidebutton (context context, AttributeSet Attrs) {Super (context, attrs); Initbitmap ();} private void Initbitmap () {SLIDEBUTTONBG = Bitmapfactory.decoderesource (Getresources (), R.drawable.slide_button_ background); SWITCHBG = Bitmapfactory.decoderesource (Getresources (), R.drawable.switch_bacKground);} /** * Mobile Effect processing */@Overridepublic Boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case Motionevent.action_down://Finger press CurrentX = (int) event.getx (); issliding = True;break;case Motionevent.action_move:// Finger move currentx = (int) event.getx () break;case motionevent.action_up://finger lift issliding = false;//Judging the current slider, on which side, If the center point of the slide block < The center point of the background is set to off state int bgcenter = Switchbg.getwidth ()/2;boolean states = CurrentX >= bgcenter; Changed state//when the finger is lifted, the callback listens, returning the current switch status if (state! = CurrentState && Mlistener! = null) {Mlistener.ontogglestatechange ( State);} CurrentState = State;break;default:break;} Invalidate (); Refreshes the control, which invokes the OnDraw (canvas canvas) method to return true; Handle events yourself, do not let the parent class consume events}/** * When measuring the current control wide height callback */@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//TODO auto-generated method Stubsuper.onmeasure (Widthmeasurespec, heightmeasurespec);// Set the width and height of the switch setmeasureddimension (Switchbg.getwidth (), Switchbg.getheight ());} /** * Draw Controls */@Overrideprotected void OnDraw (canvas canvas) {//TODO auto-generated method Stubsuper.ondraw (canvas);//1, slide switch background drawn to control Canvas.drawbitmap ( SWITCHBG, 0, 0, NULL);//2, draw the position of the slider display, turn on or off if (issliding) {int left = Currentx-slidebuttonbg.getwidth ()/2;//handle finger contacts, The contact is moved from the left side of the Slidingbutton to the middle if (< 0) {left = 0;} else if (Ieft > Switchbg.getwidth ()-slidebuttonbg.getwidth ()) {L EFT = Switchbg.getwidth ()-Slidebuttonbg.getwidth ();} Canvas.drawbitmap (SLIDEBUTTONBG, left, 0, null);} else {if (currentstate) {//Draw open State Canvas.drawbitmap (SLIDEBUTTONBG, Switchbg.getwidth ()-slidebuttonbg.getwidth (), 0, NULL);} else {//Draw off state Canvas.drawbitmap (SLIDEBUTTONBG, 0, 0, null);}}} public void Settogglestate (Boolean b) {currentstate = b;} /** * External Setup monitoring method * * @param listener */public void Setontogglestatechangelistener (Ontogglestatechangelistener listener) {th Is.mlistener = Listener;}}
The "switch button" is implemented by inheriting from view, about the view's constructor:

Public Slidebutton (Context context) {super (context);//TODO auto-generated constructor stub}
The construct is used to instantiate the component only in code and cannot be declared in the layout file

Public Slidebutton (context context, AttributeSet Attrs) {Super (context, attrs);//TODO auto-generated constructor stub}
After declaring the construct, you can declare the control in the layout file, and the general custom component will replicate the construction method.

Public Slidebutton (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, defstyle);//TODO Auto-gener Ated constructor stub}
This is the third construct of view, which can be declared in the layout file, and the component's display style needs to be made less.

After the constructor of the parent view is replicated, there are two other important ways to replicate the view, Onmeasure and OnDraw. Onmeasure is a method for measuring the size and height of a component, where only the width of the background of the "switch button" is handled, and the measured value is specified using the Setmeasureddimension method. And then in the OnDraw method, draw the custom component on canvas, it will contain a series of logic judgments, please read the source code, here is not introduced.

In order to enhance the user experience of the "switch button", it is necessary to determine the button's sliding direction to confirm the state of the button, so a carbon ontouchevent method is needed to deal with the various states of finger triggering in this method. It is worth mentioning that after processing the trigger of the finger movement, the next step is to redraw the component to achieve a dynamic effect, when each trigger must be completed, call the view's invalidate () method, the function is: Refresh the control, the method will call OnDraw (Canvas Canvas) method.

Finally, the "development button" is intended to interact or state pass with the interface or user that uses the control, and here a Java callback function is written to callback the status of the Listening "switch button" on the main interface, the code is as follows:

Package com.example.slidebutton.view.interf;/** * Switch Status change listener event *  * @author Administrator *  */public interface Ontogglestatechangelistener {/** * When switch state changes callback this method *  * @param b *            current switch's latest state */void Ontogglestatechange (Boolean b);}

For an internal implementation of the listener, refer to the Slidingbutton Custom component code. This is mainly for external reference to the interface of the control provides a way to set the listener Setontogglestatechangelistener (Ontogglestatechangelistener listener), in judging each time the finger lift, The process of changing the switch state is complete, where the callback parameter is set for the listener, that is, the status of the current switch, a Boolean variable. In this way, the interface that references the control externally can get the Boolean value and handle it accordingly. So, here's the main code that externally references the custom component:

Layout file, 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 " >    <com.example.slidebutton.view.slidebutton        android:id= "@+id/slidebutton"        android:layout_ Width= "Wrap_content"        android:layout_height= "wrap_content"        android:layout_centerinparent= "true"/> </RelativeLayout>
The main interface code Mainactivity.java:

Package Com.example.slidebutton;import Com.example.slidebutton.view.slidebutton;import Com.example.slidebutton.view.interf.ontogglestatechangelistener;import Android.os.bundle;import Android.widget.toast;import Android.app.activity;public class Mainactivity extends Activity implements Ontogglestatechangelistener {public Slidebutton Slidebutton; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); SlideButton = ( Slidebutton) Findviewbyid (R.id.slidebutton); Slidebutton.settogglestate (true); Slidebutton.setontogglestatechangelistener (this);} @Overridepublic void Ontogglestatechange (Boolean b) {//TODO auto-generated method stubif (b) {Toast.maketext ( Mainactivity.this, "Switch on", Toast.length_short). Show (); else {toast.maketext (mainactivity.this, "switch Off", Toast.length_short). Show ();}}

Here's how to run:

The above content, there are many unprofessional incorrect or negligent place, welcome everyone criticize correct, learn together ~


Please download the source code here



Android custom Controls--Imitation iOS switch button

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.