Android custom control-ios-like button

Source: Internet
Author: User
Tags call back

Android custom control-ios-like button

 

When we develop client products in the company, we will find that the difference between android and ios is that ios has benefited from the elaborate design of "Old Joe", and the interface user experience has been superb. android adheres to the open-source idea, the hundreds of user experience interfaces have their own length and cannot be consistent with each other. Let's not talk nonsense. First, look at the ios "switch button ":

 

Often in companies, the product design prototype gives priority to the ios design. This makes android Developers suffer, and android Developers are forced to write almost the same effect as ios. This situation should be very common! For example, the "switch button" I mentioned below is integrated in ios and used for use. However, the ToggleButton component does appear in android 4.0 and later, aside from the interface (actually not very beautiful), let's take a look at compatibility. ToggleButton is something that started after 4.0, so we cannot ignore 2.3 of the system, the market share of 2.3 is still very large. Therefore, the "switch button" that can achieve the same effect as ios can only be "hard" to draw such a component using java code.

A Brief Introduction to the method of the Self-painting component. In Android, the self-painting component can be divided into inherited View and inherited ViewGroup.

Implementation steps and corresponding methods:
Measure width and height --> layout (layout control position) --> draw to screen
|
OnMeasure onLayout onDraw
It is worth noting that if a custom component inherits the ViewGroup, the preceding three steps must be implemented, especially the layout. The display position of the component must be determined here. If the custom component inherits the View, you do not need to complete the layout step. You only need to complete the measurement and drawing.

The Demo structure of my project is as follows:

The main implementation code of the custom "switch button" is as follows:

 

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 {/** Sliding switch background */private Bitmap slideButtonBG;/** sliding block background */private Bitmap switchBG;/** set the switch status, on/off. Default Value: */private boolean currentState = false;/** the moving distance of the current slider */private int currentX;/** records the sliding status of the current slider. Default Value: false */private boolean isSliding = false;/** listener for changing the switch status */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_back Ground);}/*** mobile effect Processing */@ Overridepublic boolean onTouchEvent (MotionEvent event) {switch (event. getAction () {case MotionEvent. ACTION_DOWN: // press currentX = (int) event with your finger. getX (); isSliding = true; break; case MotionEvent. ACTION_MOVE: // move your finger currentX = (int) event. getX (); break; case MotionEvent. ACTION_UP: // finger-up isSliding = false; // determines which side of the current slider is biased towards. If the center of the slider is <center of the background, set to disabled int bgCenter = switchBG. getWidth ()/2; boolean state = currentX> = bgCenter; // when the finger is raised, the callback listener returns the current switch status if (state! = CurrentState & mListener! = Null) {mListener. onToggleStateChange (state);} currentState = state; break; default: break;} invalidate (); // refresh the control. This method calls the onDraw (Canvas canvas) method to return true; // handle events by yourself, so that the parent class is not responsible for consuming events}/*** callback when the current control width is high */@ 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 control */@ Overrideprotected void onDraw (Canvas canvas) {// TODO Auto-generated method stubsuper. onDraw (canvas); // 1. Draw the sliding switch background to the control canvas. drawBitmap (switchBG, 0, 0, null); // 2, draw the position displayed by the sliding block, enable or disable if (isSliding) {int left = currentX-slideButtonBG. getWidth ()/2; // process the Finger Contact and move the contact from the left of the slidingButton to the middle if (left <0) {left = 0;} else if (left> switchBG. getWidth ()-slideButtonBG. getWidth () {left = switchBG. getWidth ()-slideButtonBG. getWidth ();} canvas. drawBitmap (slideButtonBG, left, 0, null);} else {if (currentState) {// draw the canvas in the open state. drawBitmap (slideButtonBG, switchBG. getWidth ()-slideButtonBG. getWidth (), 0, null);} else {// draw the disabled canvas. drawBitmap (slideButtonBG, 0, 0, null) ;}} public void setToggleState (boolean B) {currentState = B ;} /*** listener setting method ** @ param listener */public void setOnToggleStateChangeListener (OnToggleStateChangeListener listener) {this. mListener = listener ;}}
The "switch button" is implemented by inheriting from the View. The constructor of the View is as follows:

 

 

public SlideButton(Context context) {super(context);// TODO Auto-generated constructor stub}
This structure is used to instantiate the component only in the 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 constructor, you can declare the control in the layout file. Generally, custom components rewrite the constructor.

 

 

public SlideButton(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// TODO Auto-generated constructor stub}
This is the third structure of the View. In addition to declarations in the layout file, you also need to specify the display style of the component, which is rarely used.

 

After the constructor of the parent class View is rewritten, the other two important methods of View need to be rewritten, onMeasure and onDraw. OnMeasure is used to measure the size and width of a component. Here, only the width and height of the background image of the "switch button" are processed. Use setMeasuredDimension to specify the value after measurement. In the onDraw method, draw the custom component on the Canvas, which contains a series of logical judgments. Please read the source code carefully.

To enhance the user experience of the "switch button", You need to determine the sliding direction of the button to determine the button status. Therefore, you need to rewrite the onTouchEvent method to process various statuses triggered by the finger in this method. It is worth mentioning that after processing the trigger of finger movement, the next step is to redraw the component to achieve dynamic results. At this time, each time the trigger is complete, call the invalidate () method of View to refresh the control. This method calls the onDraw (Canvas canvas) method.

Finally, the "Development button" must interact with the interface or user that uses the control or pass the status. Here, you need to write a Java callback function, it is used to call back and listen to the "switch button" status on the main interface. The Code is as follows:

 

Package com. example. slidebutton. view. interf; /*** Switch Status Change listener ** @ author Administrator **/public interface OnToggleStateChangeListener {/*** call back this method when the switch status changes ** @ param B * current switch */void onToggleStateChange (boolean B );}

For the internal implementation of the listener, see the SlidingButton custom component code. Here, we provide a method to set the listener for external reference to the control interface. setOnToggleStateChangeListener (OnToggleStateChangeListener listener) indicates the end of the process of switching the switch status when you determine that each finger is lifted, you need to set the callback parameter for the listener, that is, the boolean variable of the current switch status. In this way, you can obtain the boolean value on the external interface that references the control and perform corresponding processing. The following is the main code that references the custom component externally:

 

Layout file, activity_main.xml:

 

     
  
 
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: Toast. LENGTH_SHORT ). show ();} else {Toast. makeText (MainActivity. this: Toast. LENGTH_SHORT ). show ();}}}

Run the following command:

 

The above content has many inspecies that are incorrect or neglected. You are welcome to criticize and correct them and learn from them ~

 

 

 

 

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.