We often see a lot of great apps with some very beautiful controls, and the user experience is great. For example, ToggleButton is a very good example, the iOS system below the exquisite ToggleButton now can be implemented under Android, but also can define its own color text background, make a variety of beautiful switch button out.
Here is a more often used technology in Android-Define your own controls.
Let's take a look at our own definition of ToggleButton:
To define your own controls:
1. First, define a class that inherits the subclass of view or view, depending on the type of control you want to define. In this case, inherit from view.
2, inherit the view after the need to rewrite the constructor, there are three methods, each naturally
Public MyView (Context context) {super (context);//TODO auto-generated Constructor Stub}public MyView (context context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);//TODO auto-generated constructor stub} Public MyView (context context, AttributeSet Attrs) {Super (context, attrs);//TODO auto-generated constructor stub
These three methods. Depending on the situation, the third constructor is used assuming that the control you define needs to set the XML property. Assuming that you need to set an XML attribute and define a style, you need to implement the second constructor, using its third parameter, defstyleattr, assuming that there are no more than two points required, then rewrite the first constructor directly.
In this demo, we can implement the first constructor to
Public ToggleButton (context context, AttributeSet Attrs) {Super (context, attrs); Initbitmap ();//Initialize bitmap}
After overriding the constructor, you will then choose whether to override the OnDraw and Onmeasure methods based on the requirements of the different controls.
Assuming that you define the size of a control that you need to define, such as the ToggleButton in this example, you first need to rewrite the Onmeasure method to calculate the width and height of the control you define.
It is very obvious that the width and height of our ToggleButton is very easy to get out, height is the width of the control background map and high
So the Onmeasure method overrides such as the following to get the width and height of the control you define
/** * Initialize switch picture */private void Initbitmap () {background = Bitmapfactory.decoderesource (Getresources (), R.drawable.switch_ background); Slidebackground = Bitmapfactory.decoderesource (Getresources (), r.drawable.slide_button_background);}
/** * Sets the width and height of the current control */@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure ( Widthmeasurespec, Heightmeasurespec);//Set switch width and height setmeasureddimension (background.getwidth (), Background.getheight ( ));}
When you get the width and height, you need to draw the control. Using the OnDraw method of view
Rewrite the OnDraw method, we can get a reference canvas
void OnDraw (canvas canvas)
With this canvas object, you'll be able to draw out the controls in a very good way.
The background of the control is drawn first, due to ToggleButton. It's actually a button. Sliding back and forth on a background graph produces different effects. So let's draw its background first.
Canvas.drawbitmap (background, 0, 0, NULL);
After you finish drawing the background, you will draw a small slider. There are two states of a small slider, one is sliding, and the other is a delicate state, which we need to deal with separately.
When the slider is sliding, the background image does not change and it is clear that it slides to a certain moment. Slide how much distance you draw it at a certain distance in the state. However, there is a situation that needs to be dealt with, that is, the slide slide out of the boundary, assuming that the boundary from the left side, then it should be left to the distance of 0, that is, do not let it continue to slide, as well as the right side of the corresponding processing.
The sliding procedure code is as follows:
if (issliding) {//is sliding in int left = Currentx-slidebackground.getwidth ()/2;if (Ieft < 0) {//is currently out of bounds, assignment is 0left = 0;} E LSE if (Left > (Background.getwidth ()-slidebackground.getwidth ())) {//is currently outside the right bounds, assigned to: Width of the background-the width of the slider is left = background. GetWidth ()-Slidebackground.getwidth ();} Canvas.drawbitmap (Slidebackground, left, 0, null);}
Delicate state, very easy, depending on the state of the slider is placed on the left and right of the control can be
if (currentstate) {//Draw open State Canvas.drawbitmap (slidebackground, 0, 0, null);} else {//Draw off state int left = Background.getwidth ()-Slidebackground.getwidth (); Canvas.drawbitmap (Slidebackground, left, 0, null);}
Above, we're done. Define a ToggleButton interface, but the function of ToggleButton is to control the switch. So we have to deal with some of its events.
The handling of sliding events. Captures the user's actions. Set a self-defined state change listener for it
/** * Capture User Action Event */@Overridepublic Boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case MotionEvent.ACTION_DOWN:currentX = (int) event.getx (); issliding = True;break;case MotionEvent.ACTION_MOVE:currentX = ( int) event.getx (); Break;case MotionEvent.ACTION_UP:isSliding = False;currentx = (int) event.getx (); int center = Background.getwidth ()/2;//current status Boolean state = CurrentX < center;//Assume that two states are different and that the listener event is not NULLIF (currentstate! = State && Montogglestatechangelistener! = null) {//invokes the user's callback event Montogglestatechangelistener.ontogglestatechange ( State);} CurrentState = State;break;default:break;} Invalidate (); This method is called to cause the OnDraw method to redraw return true;}
Here, you define a state change listener. Used to listen for ToggleButton state changes, and then callback method, the corresponding processing.
public interface Ontogglestatechangelistener {void Ontogglestatechange (Boolean);}
At last. Provides three methods for this control, setting the method that has the state on or off. Another way to set up listener events
/** * Set the status of the switch * * @param state */public void Settogglestate (Boolean) {currentstate = states;} public Boolean gettooglestate () {return currentstate;} public void Setontogglestatechangelistener (Ontogglestatechangelistener listener) {Montogglestatechangelistener = Listener;}
Here, the whole process of customizing the ToggleButton is done. Then we can use the custom control in the program.
In an XML file, you use the full pathname to define your own control, and then in Java code you can get the object and related methods of this own defined control.
<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.yang.togglebutton.togglebutton android:id= "@+id/togglebutton" android:layout_width= " Wrap_content " android:layout_height=" 30dip " android:layout_centerinparent=" true "/> < Com.yang.togglebutton.ToggleButtonVIPS android:id= "@+id/toggle2" android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@+id/togglebutton" android:layout_ Centerhorizontal= "true"/></relativelayout>
A summary of the fact is a few steps:
1, inherit view or its subclass, rewrite different constructors according to different situations (must)
2. Override the Onmeasure method to measure the size of the control (not required)
3. Override the OnDraw method to draw the control (not required)
4. Set some self-defined methods and listeners for the control (not required)
5. Use in XML. or use it directly in Java code.
Reprint please specify the source http://blog.csdn.net/csr_yang/article/details/37341221
Demo download
Android App--Define your own control ToggleButton