This article illustrates the sliding switch effect of Android programming. Share to everyone for your reference, specific as follows:
Idle all right, put a demo before write to share under. is a switch that enables sliding and animation effects. Not a picture switch.
Well, first of all, here's the picture:
Full instance code click here to download the site.
Directly put the custom view code up, there should be a good understanding of comments:
The first is the layout:
<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "android:id=" @+id/sv_container "android:layout_width=" 230dip "android:layout_height=" 38dip "android:backgr ound= "@drawable/usage_list_dark" > <imageview android:id= "@+id/iv_switch_cursor" android:layout_width= "120
Dip "android:layout_height=" 36dip "android:layout_centervertical=" true "android:layout_marginleft=" 0.5dip " android:layout_marginright= "0.5dip" android:background= "@drawable/usage_list_green"/> <linearlayout Andr
Oid:layout_width= "Fill_parent" android:layout_height= "fill_parent" android:gravity= "center" > <TextView Android:id= "@+id/switch_text_true" android:layout_width= "wrap_content" android:layout_height= "Wrap_conte" NT "android:layout_weight=" 1 "android:gravity=" center "android:text=" open "/> <textview and Roid:id= "@+id/switch_text_false"Android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout_weight=" 1 "
android:gravity= "center" android:text= "off"/> </LinearLayout> </RelativeLayout>
The
is followed by the code for this view, inherited from LinearLayout:
Package Com.lxb.switchdemo;
Import Android.content.Context;
Import Android.graphics.Color;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.LayoutInflater;
Import android.view.MotionEvent;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import android.view.animation.Animation;
Import Android.view.animation.Animation.AnimationListener;
Import Android.view.animation.LinearInterpolator;
Import android.view.animation.TranslateAnimation;
Import Android.widget.ImageView;
Import Android.widget.LinearLayout;
Import Android.widget.RelativeLayout;
Import Android.widget.TextView; public class SwitchView extends LinearLayout implements Onclicklistener {private static final int flag_move_true = 1; /left to mark private static final int flag_move_false = 2; Swipe right to identify private static final int handle_layout_cursor = 100; Handle the layout method of invoking the switch private context context; Context object private Relativelayout Sv_container; SwitchView's outer layout private ImageviEW iv_switch_cursor; Switch Mail ImageView private TextView switch_text_true; True of the text information control private TextView switch_text_false; False text information Control Private Boolean ischecked = true; Whether the private Boolean Checkedchange = False has been opened; IsChecked whether there is change private oncheckedchangelistener oncheckedchangelistener; Used to monitor ischecked whether there is a change in the private int margin = 1; Cursor off edge position (this value depends on the picture, mainly for the picture can be displayed correctly) private int bg_left; Background left private int bg_right; Background right private int cursor_left; The left part of the cursor is private int cursor_top; The top of the cursor is private int cursor_right; The right part of the cursor is private int cursor_bottom; Cursor bottom private Animation Animation; Mobile animation private int currentflag = Flag_move_true;
Current move Direction Flag public SwitchView (context) {super (context);
This.context = context;
Initview (); @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {super.onlayout (changed, L, T, R
, b);
Gets the desired value Bg_left = Sv_container.getleft (); Bg_right = Sv_contaiNer.getright ();
Cursor_left = Iv_switch_cursor.getleft ();
Cursor_top = Iv_switch_cursor.gettop ();
Cursor_right = Iv_switch_cursor.getright ();
Cursor_bottom = Iv_switch_cursor.getbottom (); Private Handler Mhandler = new Handler () {@Override public void handlemessage (message msg) {switch (msg . What) {case HANDLE_LAYOUT_CURSOR:iv_switch_cursor.layout (cursor_left, Cursor_top, Cursor_right, Cursor_bo
Ttom);
Break
}
}
};
The public void OnClick (View v) {//control clicks on the trigger changes the checked value if (v = = this) {changechecked (!ischecked); }/** * Initialization control/private void Initview () {Layoutinflater inflater = (layoutinflater) context.getsystems
Ervice (Context.layout_inflater_service);
View view = Inflater.inflate (R.layout.switch_view, this);
View.setonclicklistener (this);
Sv_container = (relativelayout) View.findviewbyid (R.id.sv_container); Switch_text_true = (TextView) View.findviewbyid (r.id.switCh_text_true);
Switch_text_false = (TextView) View.findviewbyid (R.id.switch_text_false);
Changetextcolor ();
Iv_switch_cursor = (ImageView) View.findviewbyid (r.id.iv_switch_cursor);
Iv_switch_cursor.setclickable (FALSE); Iv_switch_cursor.setontouchlistener (New Ontouchlistener () {int lastx;//last X coordinates public boolean ontouch (View V , motionevent event) {switch (event.getaction ()) {Case MotionEvent.ACTION_DOWN:lastX = (int) E
VENT.GETRAWX ();
Cursor_left = V.getleft ();
Cursor_top = V.gettop ();
Cursor_right = V.getright ();
Cursor_bottom = V.getbottom ();
Break
Case MotionEvent.ACTION_MOVE:int dx = (int) event.getrawx ()-lastx;
Cursor_left = v.getleft () + dx;
Cursor_right = v.getright () + dx;
Exceeded boundary processing if (cursor_left <= bg_left + margin) {cursor_left = bg_left + margin; Cursor_right = Cursor_left + v.GetWidth ();
} if (Cursor_right >= bg_right-margin) {cursor_right = Bg_right-margin;
Cursor_left = Cursor_right-v.getwidth ();
} v.layout (Cursor_left, Cursor_top, Cursor_right, Cursor_bottom);
LASTX = (int) event.getrawx ();
Break
Case MotionEvent.ACTION_UP:calculateIscheck ();
Break
return true;
}
}); /** * Evaluates to a true or false area and makes a change processing/private void Calculateischeck () {Float Center = (float) (bg_right-b
G_left)/2.0);
float Cursor_center = (float) ((cursor_right-cursor_left)/2.0);
if (cursor_left + cursor_center <= Center) {changechecked (true);
else {changechecked (false);
}/** * Change checked, checked move cursor * @param ischecked/private void Changechecked (Boolean ischecked) {
if (this.ischecked!= ischecked) {Checkedchange = true; else {CheckedcHange = false;
} if (ischecked) {currentflag = Flag_move_true;
else {currentflag = Flag_move_false;
} cursormove (); /** * Cursor Mobile/private void Cursormove () {//Here's a point, the animation can set the Animation.setfillafter (TRUE)//To stop the animation after the last Position.
But here's how to use it.
Drag the picture again will be an exception (for specific reasons I did not find)//So the last can only use the Onanimationend callback mode layout cursor animation = NULL;
final int ToX;
if (Currentflag = = flag_move_true) {ToX = Cursor_left-bg_left-margin;
Animation = new Translateanimation (0,-tox, 0, 0);
else {ToX = Bg_right-margin-cursor_right;
Animation = new Translateanimation (0, ToX, 0, 0);
} animation.setduration (100);
Animation.setinterpolator (New Linearinterpolator ());
Animation.setanimationlistener (New Animationlistener () {public void Onanimationstart (animation animation) {} public void Onanimationrepeat (Animation Animation) {} public void Onanimationend (Animation animatiON) {//calculate where the cursor should be after the animation completes if (Currentflag = flag_move_true) {cursor_left-= ToX;
Cursor_right = Cursor_left + iv_switch_cursor.getwidth ();
else {cursor_right = Bg_right-margin;
Cursor_left = Cursor_right-iv_switch_cursor.getwidth (); }//Here can not immediately layout cursor correct position, otherwise there will be a little splash screen//In order to beautiful, here a little bit late call layout method, will not splash screen Mhandler.sendemptymessagedela
Yed (Handle_layout_cursor, 5);
This is based on whether the ischecked value is changed to perform some operations if (checkedchange) {ischecked =!ischecked;
if (Oncheckedchangelistener!= null) {oncheckedchangelistener.oncheckedchanged (ischecked);
} changetextcolor ();
}
}
});
Iv_switch_cursor.startanimation (animation); /** * Change font display color */private void Changetextcolor () {if (ischecked) {Switch_text_true.settextcolor (Col Or.
White);
Switch_text_false.settextcolor (Color.gray); else {SwitCh_text_true.settextcolor (Color.gray);
Switch_text_false.settextcolor (Color.White);
}/** * Layout cursor/private void Layoutcursor () {if (ischecked) {cursor_left = bg_left + margin;
Cursor_right = bg_left + margin + iv_switch_cursor.getwidth ();
else {cursor_left = Bg_right-margin-iv_switch_cursor.getwidth ();
Cursor_right = Bg_right-margin;
} iv_switch_cursor.layout (Cursor_left, Cursor_top, Cursor_right, Cursor_bottom); /** * ischecked Value changes listener/public interface Oncheckedchangelistener {void OnCheckedChanged (Boolean Ischecke
D);
public Boolean ischecked () {return ischecked;
} public void Setchecked (Boolean ischecked) {if (this.ischecked!= ischecked) {this.ischecked = ischecked;
if (Oncheckedchangelistener!= null) {oncheckedchangelistener.oncheckedchanged (ischecked);
} layoutcursor (); }} public void Setoncheckedchangelistener (onchEckedchangelistener oncheckedchangelistener) {this.oncheckedchangelistener = Oncheckedchangelistener;
}
}
Finally, the activity uses this view:
Package Com.lxb.switchdemo;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.LinearLayout;
Import Android.widget.TextView;
Import Android.widget.Toast;
Import Com.lxb.switchdemo.SwitchView.OnCheckedChangeListener;
public class Switch_demoactivity extends activity implements Onclicklistener {private linearlayout layout;
Private TextView Tv_showcheck;
Private SwitchView SV;
Private Button btn_set_true;
Private Button Btn_set_false;
Private Button btn_getstate;
@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Layout = (linearlayout) Findviewbyid (r.id.layout);
Tv_showcheck = (TextView) Findviewbyid (R.id.tv_showcheck);
SV = new SwitchView (this);
Tv_showcheck.settext ("Current state:" + getState (sv.ischecked ())); Sv.setoncheckedchangelistener (New OncheckeDchangelistener () {public void OnCheckedChanged (Boolean ischecked) {tv_showcheck.settext ("Current state:" + Getsta
Te (ischecked));
}
});
Layout.addview (SV);
Btn_set_true = (Button) Findviewbyid (r.id.btn_set_true);
Btn_set_false = (Button) Findviewbyid (R.id.btn_set_false);
Btn_getstate = (Button) Findviewbyid (r.id.btn_getstate);
Btn_set_true.setonclicklistener (this);
Btn_set_false.setonclicklistener (this);
Btn_getstate.setonclicklistener (this);
public void OnClick (View v) {switch (V.getid ()) {case r.id.btn_set_true:sv.setchecked (true);
Break
Case r.id.btn_set_false:sv.setchecked (FALSE);
Break Case R.id.btn_getstate:toast.maketext (Switch_demoactivity.this, sv.ischecked () + "", Toast.length_short).
Show ();
Break
} Private String GetState (Boolean state) {if (state) {return "open";
Return to "off";
}
}
Implementation is still very simple, mainly or coordinate what needs to be calculated and adjusted.
Of course, there will be a number of bugs exist, there is a need to go down to modify their own, you can also discuss with me.
For more information on Android-related content readers can view the site topics: "The Android Communication method Summary", "Android Debugging techniques and common problem solving method summary", "Android Development introduction and Advanced Course", "Android Multimedia operation tips Summary (audio, Video, audio, etc.), "Summary of Android Basic components usage", "Android View Overview", "Android Layout layout skills Summary" and "Android Control usage Summary"
I hope this article will help you with the Android program.