Android Custom View Implementation Switch button _android

Source: Internet
Author: User
Tags constructor

Introduction: Android Custom view for beginners and even work for a few years of programmers are very afraid, but also is the Android advanced learning, peacetime projects often have some harsh requirements, we can find a variety of GitHub on the effect, can use, You can't use your own time to change it. However, with the work experience and the nature of the work, it is increasingly felt that customizing the view is the time to take some effort to study.

One, after these two days of efforts, I also tried to write a demo, the effect is very simple, is the implementation of the switch button.

Some people may say that this effect so easy, find the UI cut three map on the finished, why the big fee to customize. You're right, but this is just for learning custom view to show such a common case.

Custom controls

1. Why Customize view?

Android's own controls don't meet your needs, and you need to define controls based on your needs.

2.Android interface drawing process?

The Onmeasure ()--onlayout ()--ondraw () method is executed after the Onresume () method of the activity lifecycle.

3.Android How to customize view?

Integrated View:view Process

Onmeasure () (in this method specifies its own width-height)-> onDraw () (drawing its own content)

Integrated Viewgroup:viewgroup Process

Onmeasure () (specifies its own height, width of all child view)-> OnLayout () (Placing all child view)-> OnDraw () (Drawing content)

Custom View Implementation Switch button steps:

Write a class to inherit view,

Copy contains the full path of the package name to XML,

interface, set the initial information,

Draw the interface content according to the requirement,

In response to a user's touch event,

Create a status update listener.

1. Custom Toggleview integrated view, and re-three construction methods.

Note: Why do you want to rewrite three?

Toggleview (context context) A parameter is constructed using the code that is invoked when the control is created.

Toggleview (context context, AttributeSet attrs) for use in XML, you can specify custom attributes

Toggleview (context, AttributeSet attrs, int defstyle) is used in XML to specify custom attributes, and if a style is specified, go to this constructor

We have defined the background picture, the switch button picture and the switch default state in XML, to get the attribute defined in the XML file is obtained by using the Typedarray class in the construction method that contains three parameters.

Declaring nodes in Attrs.xml declare-styleable

 <declare-styleable name=" Toggleview "> <attr name=" switch_background "format=" Reference "/> <attr name=" Slide_button "format=" reference "/> <attr name=" Switch_state "format=" boolean "/&
Gt </declare-styleable>/** * Used in XML to specify custom attributes, if a style is specified, go to this constructor * @param context * @param attrs * @param defstyle * /Public Toggleview (context, AttributeSet attrs, int defstyle) {Super (context, attrs, defstyle);//Get configured custom properties Ty
Pedarray a = Context.gettheme (). Obtainstyledattributes (Attrs, R.styleable.toggleview, Defstyle, 0);
int switchbackgroundresource = A.getresourceid (R.styleable.toggleview_switch_background,-1);
int slidebuttonresource = A.getresourceid (R.styleable.toggleview_slide_button,-1);
Mswitchstate = A.getboolean (R.styleable.toggleview_switch_state, false);
After obtaining the background picture and the switch picture, sets the picture, facilitates in the Onmeasure () method to set the view width and height, prevents the null setswitchbackgroundresource (Switchbackgroundresource);
Setslidebuttonresource (Slidebuttonresource);
Init (); }

2. After customizing Toggleview integration view, don't forget to add namespaces in the XML file

"Xmlns:cb=" Http://schemas.android.com/apk/res-auto ""

Then paste the full path of the custom view into the XML, similar to the Viewpager control under the Android V4 package

The following is the XML file code in Demo:

Set Switch background picture

-cb:switch_background= "@drawable/switch_background"

Set Switch button picture

-cb:slide_button= "@drawable/slide_button"

Set switch default state

-Cb:switch_state= "false"

3. Find the control in the interface, set the initial information

The custom view control is found in the activity by the Findviewbyid method, which is not different from the system's component operations.

Private Toggleview Toggleview;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
Toggleview = (Toggleview) Findviewbyid (R.id.toggleview);
Toggleview.setswitchbackgroundresource (r.drawable.switch_background);
Toggleview.setslidebuttonresource (R.drawable.slide_button);
Toggleview.setswitchstate (true); 
//Set Switch update listener
toggleview.setonswitchstateupdatelistener (new Toggleview.onswitchstateupdatelistener () {
@Override public
void Onstateupdate (Boolean state) {
toast.maketext (Getapplicationcontext (), "state : "+ state, Toast.length_short). Show ();}}
);

4. Draw the interface content according to the requirement

The width and height of the view has been set through the Onmeasure () method, and the following operations begin drawing in the OnDraw () method, OnDraw (Canvas Canvas) method Canvas parameters: Canvas, artboard. The content drawn on the top will be displayed to the interface.

Depending on the switch state Boolean, directly set the picture position
if (mswitchstate) {//open
int newleft = Switchbackgroupbitmap.getwidth ()- Slidebuttonbitmap.getwidth ();
Canvas.drawbitmap (Slidebuttonbitmap, newleft, 0, paint);
} else {//off
canvas.drawbitmap (slidebuttonbitmap, 0, 0, paint);
}

When the switch is turned on, the position of the switch button is calculated in the position of the switch background:

 
 

Slidebuttonbitmap.getwidth (); Width of the background-the width of the button is the position on the x-axis of the current toggle button

The position point on the x-axis where the current switch button is on when the switch is off =0

5. Responding to User touch events

After completing the 3 steps above, you will find that only after the first entry of the XML initialization of the default switch state of the Boolean value will be changed, then click is no effect, this time we have to find ways to monitor gestures events, rewrite ontouchevent (motionevent Event) method, I believe most friends are not unfamiliar with this method.

There are three states of motionevent:

Motionevent.action_down://Press the screen
Motionevent.action_move://fingers moving on the screen
MOTIONEVENT.ACTION_UP//Off screen

The current issues to consider are:

When the finger presses the screen motionevent.action_down (in the current switch background view) The x-axis position of the switch should be moved to the position where the finger is pressed;

When the finger moves on the screen motionevent.action_move (in the current switch background view) The switch button x axis should change with the position of the finger movement;

When the finger leaves the screen motionevent.action_up (in the current switch background view) The switch button should determine whether the position of the finger left is half the current background, if the x-axis position is greater than 1/2 of the view background width, it should be open, If the x-axis position is less than 1/2 of the view background width, it should be turned off.

As shown in the figure:

Private Onswitchstateupdatelistener Onswitchstateupdatelistener;
Rewrite the touch event to respond to the user's touch. @Override public boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case MotionEvent.ACTION_DOWN:isT
Ouchmode = true;
System.out.println ("Event:action_down:" + event.getx ());
CurrentX = Event.getx ();
Break
Case MotionEvent.ACTION_MOVE:System.out.println ("Event:action_move:" + event.getx ());
CurrentX = Event.getx ();
Break
Case MotionEvent.ACTION_UP:isTouchMode = false;
System.out.println ("event:action_up:" + event.getx ());
CurrentX = Event.getx ();
Float Center = switchbackgroupbitmap.getwidth ()/2.0f; 
Compares the position of the control center with the position currently pressed.
Boolean state = currentx > center; If the switch state changes, notify the interface.
The inside switch status is updated.
if (state!= mswitchstate && onswitchstateupdatelistener!= null) {//Put up the latest Boolean, status out of the
Onswitchstateupdatelistener.onstateupdate (state);
} mswitchstate = State;
Break
Default:break; //Redraw interface invalidate (); Will cause the OnDraw () to be invoked and the variables inside will be back in effect. The interface will update return true; Consuming the user's touch thingPieces before they can receive other events. }

Attention:

Above listening ontouchevent (motionevent

Event) method, there is a problem, do not know whether we have found that we do not set the boundary value of the switch button, what do you mean? The left and right side can draw the current background when the fingers are sliding.

So there's a need to handle the x-axis position on both sides:

Canvas Canvas, artboard. The content drawn on the top will be displayed to the interface.
@Override
protected void OnDraw (Canvas Canvas) {
//1. Draw Background
Canvas.drawbitmap (switchbackgroupbitmap, 0, 0, paint);
2. Draw the slider
if (istouchmode) {
////////To draw the slider from the position where the current user touches it/
/Let the slider move to the left half of its size
float Newleft = CurrentX- Slidebuttonbitmap.getwidth ()/2.0f;
int maxleft = Switchbackgroupbitmap.getwidth ()-slidebuttonbitmap.getwidth ();
Qualifying Slider Range
if (Newleft < 0) {
newleft = 0;//Left range
}else if (Newleft > Maxleft) {
newleft = Maxleft ; Right range
}
canvas.drawbitmap (Slidebuttonbitmap, newleft, 0, paint);
} else {
///According to the switch state Boolean, directly set the picture position
if (mswitchstate) {//open
int newleft = Switchbackgroupbitmap.getwidth () -Slidebuttonbitmap.getwidth ();
Canvas.drawbitmap (Slidebuttonbitmap, newleft, 0, paint);
} else {//off
canvas.drawbitmap (slidebuttonbitmap, 0, 0, paint);}}}

6. Create a status update listener.

Basically so the work is done so that we have a custom view that is already done, and when you do that, you may find a bit like a checkbox. Since it is similar to a checkbox, we know that when the checkbox is clicked to select and uncheck, there is a ischecked () method to get the selected state, so our custom switch button naturally can not be less this function, otherwise we only have effect on the interface display, But there is no logical place to deal with.

public interface onswitchstateupdatelistener{
//status callback, passing the current state out of
void Onstateupdate (Boolean state)
;
public void Setonswitchstateupdatelistener (
onswitchstateupdatelistener onswitchstateupdatelistener) {
This.onswitchstateupdatelistener = Onswitchstateupdatelistener;
}

The code is simple, write an interface, and then define a callback method to return the state of the switch, it should be noted that, when the finger away from the screen, we need to determine whether the operation changed the state of the switch, if there is no change we do not operate, if the state is different from the last, notify the activity state changes

Case MOTIONEVENT.ACTION_UP:
Istouchmode = false;
System.out.println ("event:action_up:" + event.getx ());
CurrentX = Event.getx (); 
Float Center = switchbackgroupbitmap.getwidth ()/2.0f;
Compares the position of the control center with the position currently pressed. 
Boolean state = currentx > Center;
If the switch state changes, notify the interface. The inside switch status is updated.
if (state!= mswitchstate && onswitchstateupdatelistener!= null) {
//Put up the latest Boolean, status
out of the Onswitchstateupdatelistener.onstateupdate (state);
}
Mswitchstate = State;
Break

The callback in the activity is also very simple, similar to the Setonclicklistener callback interface provided by the Android system, which was previously defined by the system's listener interface, this time through a simple custom view, We can also give our own view write callback interface. Do you think it's a happy thing?

Set Switch Update listener
toggleview.setonswitchstateupdatelistener (new Toggleview.onswitchstateupdatelistener () {
@ Override public
void Onstateupdate (Boolean state) {
toast.maketext (Getapplicationcontext (), ' state: ' + State, Toast.length_short). Show ();
}
};

The above is a small set to introduce the Android custom view implementation Switch button, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.