We often see a lot of good apps with some nice controls on it, and the user experience is great, like ToggleButton is a great example, and the delicate ToggleButton underneath the iOS system can now be implemented under Android, And can also customize its color text background, make a variety of beautiful switch button out. Here is a more commonly used technology in Android-custom controls.
First look at the custom ToggleButton we implemented:
To customize a control:
1. First, define a class to inherit 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, respectively, is
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 are used depending on the situation, and if the custom control needs to set the XML attribute then use the third constructor, if you need to set the XML property and define the style, then you need to implement the second constructor, using its third parameter defstyleattr, If you do not have the above two points, rewrite the first constructor directly.
In this demo, we 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.
If the size of the custom control needs to be customized, such as the ToggleButton in this example, you first need to override the Onmeasure method to measure the width and height of the custom control.
Obviously, the width and height of our ToggleButton is very easy to get out of, altitude is this control background map width and height
So the Onmeasure method is rewritten as follows to get the width and height of the custom control
/** * 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 this control, using the OnDraw method of view
Rewrite the OnDraw method, we can get a parameter canvas
void OnDraw (canvas canvas)
With this Canvas object, you can draw the look of the control in a very
Draw the background of the control first, because ToggleButton is actually a button that slides back and forth on a background graph to produce 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, the other is a stationary state, and we need to deal with each of these two states separately.
When the slider is sliding, the background map will not change, and it slides to a certain moment of the appearance is also very clear, sliding how much distance to draw it at a certain distance of the state, but there is a situation that needs to be handled, that is, the slider slide out of the boundary, if the slide from the left edge, Then you should set it from the left side of the distance to 0, that is, do not let it continue to slide, the same way to the right side of the corresponding processing.
The sliding process 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);}
At rest, it is easy to place the slider to the left and right of the control according to different states
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 have finished customizing a ToggleButton interface, but the function of ToggleButton is to control the switch, so we have to deal with some of its events.
Swipe event handling, capture user actions, set a custom 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;//If two states are different and 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;}
A state change listener is defined here to monitor the state change of the ToggleButton, and then the callback method is processed accordingly.
public interface Ontogglestatechangelistener {void Ontogglestatechange (Boolean);}
Finally, for this control to provide three methods, set the state to open or Close method, there is a way to set the listener event
/** * 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. Next we can use our own defined controls in the program.
In the XML file, the custom control is used with the full pathname, and then in the Java code you get the object and related methods of the custom 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>
Summing up is actually 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 custom methods and listeners for the control (not required)
5, used in XML, or directly in Java code
Reprint please specify the source http://blog.csdn.net/csr_yang/article/details/37341221
Demo download