Android custom view slide switch supports left and right slide for listview and androidlistview

Source: Internet
Author: User

Android custom view slide switch supports left and right slide for listview and androidlistview


To enable this function.

When the switch is on the left, it is gray. When sliding to the right, it changes the color and turns green;

When the switch is green on the right side, it slides to the left and changes the color to gray when it slides halfway.

The maximum sliding distance and the sliding distance are involved here. Use this to compare and change the color.


Import android. content. context; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. graphics. canvas; import android. graphics. paint; import android. graphics. porterDuff. mode; import android. graphics. porterduxfermode; import android. graphics. rect; import android. graphics. rectF; import android. util. attributeSet; import android. util. log; import android. view. motionEvent; import Droid. view. view;/*** custom Switch button, ***/public class PushSlideSwitchView extends View {/** gray style image at the bottom of the Switch */private Bitmap mSwitchBgUnseleted; /** Switch bottom Green style chart */private Bitmap mSwitchBgSeleted;/** Switch gray ball */private Bitmap mSwitchBallUnseleted;/** Switch green ball */private Bitmap mSwitchBallSeleted; private float mCurrentX = 0;/** Switch status, which is enabled by default: true */private boolean mSwitchOn = true;/** maximum Switch Movement Distance */private int mMoveLength;/** valid region for the first press */private float mLastX = 0;/** size of the target region drawn */private Rect mDest = null; /** capture the size of the source image * // ** Switch offset */private int mMoveDeltX = 0;/** Paint brush tool */private Paint mPaint = null; /** Switch Status listener interface */private OnSwitchChangedListener switchListener = null; private boolean mFlag = false;/** enabled attribute is true */private boolean mEnabled = true; /** maximum transparency, that is, opacity */private Final int MAX_ALPHA = 255;/** current transparency. It is mainly used to set the transparency when the enable attribute of the control is false, that is, you cannot click */private int mAlpha = MAX_ALPHA; /** Switch determines whether to drag */private boolean mIsScrolled = false; public PushSlideSwitchView (Context context) {this (context, null);} public PushSlideSwitchView (Context context, AttributeSet attrs) {this (context, attrs, 0);} public PushSlideSwitchView (Context context, AttributeSet attrs, int defStyle) {Super (context, attrs, defStyle); init () ;}/ *** initialize related resources */public void init () {mSwitchBgSeleted = BitmapFactory. decodeResource (getResources (), R. drawable. push_button_selected_bg); mSwitchBgUnseleted = BitmapFactory. decodeResource (getResources (), R. drawable. push_button_unselected_bg); mSwitchBallSeleted = BitmapFactory. decodeResource (getResources (), R. drawable. push_button_ball_selected); mSwitchBallUnsele Ted = BitmapFactory. decodeResource (getResources (), R. drawable. push_button_ball_unselected); mMoveLength = mSwitchBgSeleted. getWidth ()-mSwitchBallSeleted. getWidth (); // the size of the drawn area. mDest = new Rect (0, 0, mSwitchBgSeleted. getWidth (), mSwitchBgSeleted. getHeight (); mPaint = new Paint (); mPaint. setAntiAlias (true); mPaint. setAlpha (255); mPaint. setXfermode (new porterduduxfermode (Mode. DST_IN);} @ Overrideprotected vo Id onMeasure (int widthMeasureSpec, int heightMeasureSpec) {setMeasuredDimension (mSwitchBgSeleted. getWidth (), mSwitchBgSeleted. getHeight () ;}@ Overrideprotected void onDraw (Canvas canvas) {super. onDraw (canvas);/* System. out. println ("--- onDraw () --- mMoveDeltX =" + mMoveDeltX + "mSwitchBgUnseleted. getWidth () = "+ mSwitchBgUnseleted. getWidth () + "mSwitchBallSeleted. getWidth () = "+ mSwitchBallSeleted. getW Idth () + "mMoveLength =" + mMoveLength); */canvas. saveLayerAlpha (new RectF (mDest), mAlpha, Canvas. MATRIX_SAVE_FLAG | Canvas. CLIP_SAVE_FLAG | Canvas. HAS_ALPHA_LAYER_SAVE_FLAG | Canvas. FULL_COLOR_LAYER_SAVE_FLAG | Canvas. CLIP_TO_LAYER_SAVE_FLAG); // if it is disabled if (! MSwitchOn) {if (mMoveDeltX> 0) {// slide to the right if (mMoveDeltX <mMoveLength/2) {// The sliding distance is less than half the canvas. drawBitmap (mSwitchBgUnseleted, 0, 0, null); // gray background canvas. drawBitmap (mSwitchBallUnseleted, mMoveDeltX, 0, null); // gray button} else {// sliding distance greater than half canvas. drawBitmap (mSwitchBgSeleted, 0, 0, null); // green background canvas. drawBitmap (mSwitchBallSeleted, mMoveDeltX, 0, null); // green button} else {canvas. drawBitmap (mSwitchBgUnseleted, 0, 0, null); // gray Color background canvas. drawBitmap (mSwitchBallUnseleted, 0, 0, null); // gray button} else {if (mMoveDeltX <0) {// slide to the right if (Math. abs (mMoveDeltX) <mMoveLength/2) {// sliding distance less than half canvas. drawBitmap (mSwitchBgSeleted, 0, 0, null); // green background canvas. drawBitmap (mSwitchBallSeleted, mSwitchBgSeleted. getWidth ()-mSwitchBallSeleted. getWidth () + mMoveDeltX, 0, null); // green button} else {// The sliding distance is greater than half of the canvas. drawBitmap (mSwitchBgUnseleted, 0, 0, null); // gray Background canvas. drawBitmap (mSwitchBallUnseleted, mSwitchBgSeleted. getWidth ()-mSwitchBallSeleted. getWidth () + mMoveDeltX, 0, null); // gray button} else {canvas. drawBitmap (mSwitchBgSeleted, 0, 0, null); // green background canvas. drawBitmap (mSwitchBallSeleted, mMoveLength, 0, null); // green button} canvas. restore () ;}@ Overridepublic boolean onTouchEvent (MotionEvent event) {// TODO Auto-generated method stub // The touch effect is valid only when the Enabled attribute is set to true. If (! MEnabled) {return true;} switch (event. getAction () {case MotionEvent. ACTION_DOWN: mLastX = event. getX (); break; case MotionEvent. ACTION_MOVE: mCurrentX = event. getX (); mMoveDeltX = (int) (mCurrentX-mLastX); // System. out. println ("==================" + mMoveDeltX); if (mMoveDeltX> 3) {// sets the error distance of 3, you can better achieve the click Effect of mIsScrolled = true;} // If the switch is on, slide to the right, or the switch is closed to the left (this time does not need to be processed) if (mSwitchOn & mMoveDeltX> 0) | (! MSwitchOn & mMoveDeltX <0) {mFlag = true; mMoveDeltX = 0;} if (Math. abs (mMoveDeltX)> mMoveLength) {mMoveDeltX = mMoveDeltX> 0? MMoveLength:-mMoveLength;} invalidate (); break; case MotionEvent. ACTION_UP: // if it has not been swiped, it is regarded as a click event if (! MIsScrolled) {mMoveDeltX = mSwitchOn? MMoveLength:-mMoveLength; mSwitchOn =! MSwitchOn; if (switchListener! = Null) {switchListener. onSwitchChange (this, mSwitchOn);} invalidate (); mMoveDeltX = 0; break;} mIsScrolled = false; if (Math. abs (mMoveDeltX)> 0 & Math. abs (mMoveDeltX) <mMoveLength/2) {mMoveDeltX = 0; invalidate ();} else if (Math. abs (mMoveDeltX)> mMoveLength/2 & Math. abs (mMoveDeltX) <= mMoveLength) {mMoveDeltX = mMoveDeltX> 0? MMoveLength:-mMoveLength; mSwitchOn =! MSwitchOn; if (switchListener! = Null) {switchListener. onSwitchChange (this, mSwitchOn);} invalidate (); mMoveDeltX = 0;} else if (mMoveDeltX = 0 & mFlag) {// at this time, no processing is required, because mMoveDeltX = 0; mFlag = false;} default: break;} invalidate (); return true;} has been moved ;} /*** set the switch status listener **/public void setOnChangeListener (OnSwitchChangedListener listener) {switchListener = listener;}/*** switch listener interface **/public interface OnSwitchChangedLis Tener {public void onSwitchChange (PushSlideSwitchView switchView, boolean isChecked);} @ Overridepublic void setEnabled (boolean enabled) {// TODO Auto-generated method stubmEnabled = enabled; mAlpha = enabled? MAX_ALPHA: MAX_ALPHA/2; Log. d ("enabled", enabled? "True": "false"); super. setEnabled (enabled); invalidate ();}/** automatically determines to switch to the opposite property: true --> false; false --> true */public void toggle () {setChecked (! MSwitchOn);}/** set the selected status (select: true unselected: false) */public void setChecked (boolean checked) {mSwitchOn = checked; invalidate ();}}



This is a class.

You can reference an xml file as follows:

<com.app.view.PushSlideSwitchView            android:id="@+id/push_set_warm_switchview"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center"            android:layout_marginRight="15dip"            android:enabled="true" />

Add the four images to be referenced.


In java code, we set switchView. setOnChangeListener () to monitor whether to enable or disable switchView. setOnChangeListener.


For a single use, there is no problem with the above.

However, a problem is also involved here. If listview is used, if each item has such a switch, this operation scenario may be seen in the application permission settings.

Previously, other custom slide switches will find that if you slide up or down several times, it will be messy. The left side will jump to the right side, and some the right side will jump to the left side. This also solves this problem.


The java code is as follows:

Package com. example. compoundbuttonview; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import android. app. activity; import android. content. context; import android. OS. bundle; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import android. widget. listView; import android. widget. textVi Ew; import com. example. compoundbuttonview. view. mySlideSwitchView; import com. example. compoundbuttonview. view. mySlideSwitchView. onSwitchChangedListener;/***/public class MainActivity2 extends Activity {private ListView listview; List <Map <String, Object> tempListData = new ArrayList <Map <String, object >>> (); @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState ); SetContentView (R. layout. main2); initView (); for (int I = 0; I <50; I ++) {HashMap datamap = new HashMap <String, Object> (); datamap. put ("index", I + 1); datamap. put ("checked", I % 2 = 0? True: false); tempListData. add (datamap);} MyAdapter adapter = new MyAdapter (MainActivity2.this); listview. setAdapter (adapter);} private void initView () {listview = (ListView) findViewById (R. id. listView1);} class MyAdapter extends BaseAdapter {private LayoutInflater inflater = null; private Context context; public MyAdapter (Context context) {this. context = context; inflater = LayoutInflater. from (context) ;}@ Overridepublic int getCount () {return tempListData. size () ;}@ Overridepublic Object getItem (int position) {return tempListData. get (position) ;}@ Overridepublic long getItemId (int position) {return position;} public void modifyStates (int position) {}@ Overridepublic View getView (final int position, View convertView, viewGroup parent) {ViewHolder holder; if (convertView = null) {convertView = inflater. inflate (R. layout. main2_listview_item, null); holder = new ViewHolder (); holder. index = (TextView) convertView. findViewById (R. id. item_index); holder. slideSwitchView = (MySlideSwitchView) convertView. findViewById (R. id. item_SwitchView); // uses tags to store convertView data. setTag (holder);} else {holder = (ViewHolder) convertView. getTag ();} holder. index. setText (tempListData. get (position ). get ("index") + ""); holder. slideSwitchView. setChecked (Boolean) tempListData. get (position ). get ("checked"); holder. slideSwitchView. setOnChangeListener (new OnSwitchChangedListener () {@ Overridepublic void onSwitchChange (MySlideSwitchView switchView, boolean isChecked) {tempListData. get (position ). put ("checked", isChecked) ;}}); return convertView ;}} class ViewHolder {public MySlideSwitchView SlideSwitchView; public TextView index ;}}

The xml layout file is as follows:

Main2.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:android1="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:padding="1dip" >    <ListView        android1:id="@+id/listView1"        android1:layout_width="match_parent"        android1:layout_height="wrap_content" >    </ListView></LinearLayout>

Item. xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:android1="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:padding="1dip" >    <ListView        android1:id="@+id/listView1"        android1:layout_width="match_parent"        android1:layout_height="wrap_content" >    </ListView></LinearLayout>

Okay, because the code is all pasted out. I didn't make it into a resource for download, and the code was annotated. I can understand it at a Glance. It is actually very useful.



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.