Android Developer's Custom view feature (iii): Custom GridView

Source: Internet
Author: User
Tags gety

The GridView is a very powerful component used in Android development. However, we sometimes have a lot of special needs that need to be reformed on its basis. Sometimes there will be the need to move the GridView item location, this online has a lot of examples, Bo owner is not described. Today's blog is about moving the contents of the GridView item. Bloggers have not seen the online mobile item location of the demo, do not know the principle is not the same as bloggers think. Bloggers have thought about it, and it seems that the blogger's realization principle seems to be used to implement the mobile item location as well. But before Bo Master hundred can not solve the millet phone's desktop of the custom disorderly emissions, it seems to be able to use this principle to achieve. All right, no more nonsense.




Here the blogger is the number of content to demonstrate, different numbers item background color different to distinguish, long hold down an item can be moved, each move, moving item minus 1, moved to the item plus 1. The effect is OK. Well, on the code, we all learn together. Students who understand the principles of their implementation can modify the code themselves to develop the GridView for removable item

Full item: http://download.csdn.net/detail/victorfreedom/8326829

(Recent network does not give force, GitHub upload problems, and so on tomorrow the last Custom view topic, then upload all the items together, do not mind that points of the students can download first)


Package Com.freedom.gridview;import Android.annotation.suppresslint;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.pixelformat;import Android.util.attributeset;import Android.view.gravity;import Android.view.motionevent;import Android.view.view;import Android.view.viewconfiguration;import Android.view.viewgroup;import Android.view.windowmanager;import Android.view.animation.animationutils;import Android.widget.adapterview;import Android.widget.GridView;import Android.widget.imageview;import Android.widget.toast;import Com.freedom.gridview.adapter.gridviewadapter;import com.freedom.gridview.bean.data;/** * @ClassName: Freedomgridview * @author victor_freedom ([email protected]) * @ CreatedDate 2015-1-4 pm 10:25:52 * @Description: GridView */@SuppressLint ("Newapi") public class for removable item content Freedomgridview extends GridView {//Whether in move private Boolean ismove = false;//is the first time to move private Boolean IsFirst = true;//is Long press Private Boolean Islongclick = false;// Graphics private Bitmap bitmap;//mobile view private ImageView Moveview = null;//offset private int OffsetX, offsety;//the location of the touch in the screen private int touchpositioninscreen;//Move the destination private int movetoposition;//to touch the coordinates in item private int TOUCHPOSITIONINITEMX, touchpositioninitemy;//move Speed private int scaledtouchslop;//move, the upper and lower margins determine the automatic sliding distance private int upscrollbounce;private int downscrollbounce;//form Manager, for adding views private WindowManager WindowManager = Null;private windowmanager.layoutparams Layoutparams = null;private Gridviewadapter adapter;public Freedomgridview (context context) {super (context); Scaledtouchslop = Viewconfiguration.get (context). Getscaledtouchslop ();} Public Freedomgridview (context context, AttributeSet Attrs) {Super (context, attrs);} Public Freedomgridview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);} /** * Long Press decision */private Runnable Longpressrun = new Runnable () {@Overridepublic void run () {Islongclick = true;}};/ * * @Title: Contains * @Description: Determine if the touch coordinates are inside the view * @pAram V * @param xinview * @param yinview * @return * @throws */private boolean contains (View v, int xinview, int yinview) {if (v instanceof ImageView) {return ((ImageView) v). Getdrawable (). GetBounds (). Contains (Xinview, Yinview);} Return V.getbackground (). GetBounds (). Contains (Xinview, Yinview);} @Overridepublic boolean ontouchevent (motionevent ev) {//Get adapter if (NULL = = Adapter | | adapter.isempty ()) {adapter = (Gridvi Ewadapter) Getadapter ();} Switch (ev.getaction ()) {case motionevent.action_down://gets the coordinate with respect to the touch view int x = (int) ev.getx (); int y = (int) ev.gety ();//Get Touch position Touchpositioninscreen = Movetoposition = This.pointtoposition (x, y);//Determine if position is valid if (movetoposition = = Adapterview.invalid_position) {break;} Get the visible itemviewgroup of the current touch Itemview = (viewgroup) this.getchildat (Movetoposition-this.getfirstvisibleposition ());// Gets the offset of the click Position relative to the item view Touchpositioninitemy = Y-itemview.gettop (); touchpositioninitemx = X-itemview.getleft ();// Get the item view inside the control view view = Itemview.findviewbyid (r.id.desk_back);// Determine if the click position is inside the view if (This.contains (view, Touchpositioninitemx, touchpositioninitemx)) {try {int[] Locationinscreen = new Int[2];view.getlocationonscreen (Locationinscreen);} catch (NullPointerException e) {break;}} The offset at which the view is moved this.offsetx = (int) (EV.GETRAWX ()-X), this.offsety = (int) (Ev.getrawy ()-y);//gets triggered when dragging the view to the top or bottom automatically scrolls the view edge Distance upscrollbounce = math.min (Y-scaledtouchslop, GetHeight ()/3);d ownscrollbounce = Math.max (y + scaledtouchslop,getheigh T () * 2/3); itemview.setdrawingcacheenabled (true);//Bitmapbitmap with item view = Bitmap.createbitmap ( Itemview.getdrawingcache ()); Itemview.destroydrawingcache ();p ostdelayed (Longpressrun, +); break;case MotionEvent.ACTION_MOVE:if (islongclick) {int mx = (int) ev.getx (); int my = (int) ev.gety ();//First move, create mobile view if (isFirst) INI Twindowmanager (bitmap, MX, my), OnMove (MX, my);//Runableremovecallbacks (Longpressrun) before removal; return true;} Break;case MotionEvent.ACTION_UP:int upy = (int) ev.gety (); int upX = (int) ev.getx (); if (Ismove && islongclick) {sTopmove (); Completemove (UpX, upy); ismove = False;islongclick = False;break;} Removecallbacks (Longpressrun);} return super.ontouchevent (EV);} /** * @Title: Initwindowmanager * @Description: Create mobile View * @param BM * @param x * @param y * @throws */public void Initwindo Wmanager (Bitmap BM, int x, int y) {stopmove (); isFirst = False;layoutparams = new Windowmanager.layoutparams (); Layoutparam s.gravity = Gravity.top | Gravity.left;layoutparams.horizontalmargin = Layoutparams.verticalmargin = 0;layoutparams.x = X-touchpositioninitemx + Offsetx;layoutparams.y = y-touchpositioninitemy + offsety;layoutparams.width = WindowManager.LayoutParams.WRAP_ Content;layoutparams.height = Windowmanager.layoutparams.wrap_content;layoutparams.flags = windowmanager.layoutparams.flag_not_focusable| windowmanager.layoutparams.flag_not_touchable| windowmanager.layoutparams.flag_keep_screen_on| Windowmanager.layoutparams.flag_layout_no_limits;layoutparams.format = pixelformat.translucent; Layoutparams.windowanimations =0;windowmanager = (WindowManager) this.getcontext (). Getsystemservice ("window"); ImageView moveviewtemp = new ImageView (GetContext ()); Moveviewtemp.setimagebitmap (BM); WindowManager = (WindowManager) this.getcontext (). GetSystemService ("window"); Windowmanager.addview (Moveviewtemp, layoutparams); moveview = Moveviewtemp;} /** * @Title: Stopmove * @Description: Stop moving * @throws */public void Stopmove () {if (Moveview! = null) {Windowmanager.remov Eview (moveview); moveview = null;}} /** * @Title: OnMove * @Description: Method triggered when the view is moved * @param x * @param y * @throws */public void onMove (int x, int y) {Ismo ve = true;//Avoid dragging to an invalid area int tempposition = this.pointtoposition (x, y); if (tempposition! = freedomgridview.invalid_position ) {this.movetoposition = tempposition;} When moving, update the view position if (Moveview! = null) {Layoutparams.alpha = 0.8f;layoutparams.y = Y-touchpositioninitemy + OFFSETY;LAYOUTP Arams.x = X-touchpositioninitemx + offsetx;windowmanager.updateviewlayout (Moveview, layoutParams);} int scrollheight = 0;if(Y < Upscrollbounce) {scrollheight = 30;} else if (Y > downscrollbounce) {scrollheight =-30;} Trigger Auto-Scroll if (scrollheight! = 0) {smoothscrolltopositionfromtop (Movetoposition,getchildat (Movetoposition- Getfirstvisibleposition ()). GetTop () + scrollheight, 1);}} /** * @Title: Completemove * @Description: When the move is complete * @param x * @param y * @throws */public void completemove (int x, int y) {IsFirst = true;//gets the stop position int tempposition = this.pointtoposition (x, y); if (tempposition! = freedomgridview.invalid_ POSITION) {this.movetoposition = tempposition;} if (Y < Getchildat (0). GetTop ()) {return;} else if (Y > Getchildat (Getchildcount ()-1). Getbottom ()) {movetoposition = Getadapter (). GetCount ()-1;return;} else {//if in valid location if (movetoposition >= 0 && movetoposition < Getadapter (). GetCount ()) {ViewGroup Itemview = ( ViewGroup) This.getchildat (Movetoposition-this.getfirstvisibleposition ()), if (itemview! = null) {ImageView ImaveView = (ImageView) Itemview.findviewbyid (r.id.desk_back);//Determine whether to move into a valid view inside the Boolean isIn = This.contains (Imaveview,x-itemview.getleft (), Y-itemview.gettop ());//If it has been moved in, And is not the start position when touching if (isIn) {if (movetoposition! = Touchpositioninscreen) {itemview.startanimation ( Animationutils.loadanimation (GetContext (), R.anim.desk_scale));D ata Touchdata = ((Data) Adapter.getitem ( Touchpositioninscreen)), if (touchdata.getnum () = = 0) {Toast.maketext (GetContext (), "number 0 immutable", Toast.length_short). Show (); return;} Data Todata = (data) Adapter.getitem (movetoposition), if (todata.getnum () = = 2) {Toast.maketext (GetContext (), "Number 2 not changeable" , Toast.length_short). Show (); return;} Touchdata.setnum (Touchdata.getnum ()-1); Todata.setnum (Todata.getnum () + 1); adapter.notifydatasetchanged ();}}}}}}






Android Developer's Custom view feature (iii): Custom GridView

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.