Android,드래그 가능 한 GridView 효과 구현

Android 드래그 가능 한 GridView 효과 구현,길 게 누 르 면 드래그 가능 및 item 실시 간 교환
간단하게 수정 하고 원 하 는 기능 을 완성 합 니 다.길 게 누 르 고 쓰레기통 으로 이동 하여 데 이 터 를 삭제 합 니 다.

주요 사고방식 은:
1.사용자 가 길 게 누 른 동작 가 져 오기
2.누 른 그림 의 bitmap 가 져 오기 및 이동 할 때 동적 으로 미 러 새로 고침
3 action_up 시 미 러 의 위 치 를 판단 하고 논리 삭제 여부 에 들 어 갑 니 다.
사용자 정의 컨트롤

package com.leafact.GridView; 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.PixelFormat; 
import android.graphics.Rect; 
import android.os.Handler; 
import android.os.Vibrator; 
import android.util.AttributeSet; 
import android.view.Gravity; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.WindowManager; 
import android.widget.AdapterView; 
import android.widget.GridView; 
import android.widget.ImageView; 
import android.widget.Toast; 
/** 
 *      item ,      gridView 
 * 
 * @author leafact 
 * 
 */ 
public class MoveGridView extends GridView { 
  private WindowManager mWindowManager; 
  /** 
   * item        
   */ 
  private WindowManager.LayoutParams mWindowLayoutParams; 
  /** 
   *     
   */ 
  private Vibrator mVibrator; 
  //      ,   100ms 
  private long vibratorMs = 100; 
  //        1  
  private long responseMS = 1000; 
  private static boolean isMove = false; 
  //     x,y 
  private int mDownX = 0; 
  private int mDownY = 0; 
  //       x,y 
  private int mMoveX = 0; 
  private int mMoveY = 0; 
  //    x,y 
  private int mUpX = 0; 
  private int mUpY = 0; 
  private int mPoint2ItemTop; 
  private int mPoint2ItemLeft; 
  private int mOffset2Top; 
  private int mOffset2Left; 
  /** 
   *        
   */ 
  private int mStatusHeight; 
  public MoveGridView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    mVibrator = (Vibrator) context 
        .getSystemService(Context.VIBRATOR_SERVICE); 
    mWindowManager = (WindowManager) context 
        .getSystemService(Context.WINDOW_SERVICE); 
    mStatusHeight = getStatusHeight(context); //          
  } 
  //     item   ,   INVALID_POSITION=-1 
  private int mMovePosition = INVALID_POSITION; 
  /** 
   *       item   View 
   */ 
  private View mStartMoveItemView = null; 
  private ImageView mMoveImageView = null; 
  private Bitmap mMoveBitmap; 
  private Handler mHandler = new Handler(); 
  //             
  private Runnable mLongClickRunnable = new Runnable() { 
    @Override 
    public void run() { 
      isMove = true; 
      mVibrator.vibrate(vibratorMs); 
      //           item   
      createDragImage(mMoveBitmap, mDownX, mDownY); 
    } 
  }; 
  @Override 
  public boolean onTouchEvent(MotionEvent ev) { 
    switch (ev.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
      mDownX = (int) ev.getX(); 
      mDownY = (int) ev.getY(); 
      System.out.println("ACTION_DOWN"); 
      //      X,Y       item position 
      mMovePosition = pointToPosition(mDownX, mDownY); 
      //            。       
      if (mMovePosition == AdapterView.INVALID_POSITION) { 
        break; 
      } 
      mHandler.postDelayed(mLongClickRunnable, responseMS); 
      mStartMoveItemView = getChildAt(mMovePosition 
          - getFirstVisiblePosition()); 
      mPoint2ItemTop = mDownY - mStartMoveItemView.getTop(); 
      mPoint2ItemLeft = mDownX - mStartMoveItemView.getLeft(); 
      mOffset2Top = (int) (ev.getRawY() - mDownY); 
      mOffset2Left = (int) (ev.getRawX() - mDownX); 
      //   mMoveItemView     
      mStartMoveItemView.setDrawingCacheEnabled(true); 
      //   mMoveItemView     Bitmap   
      mMoveBitmap = Bitmap.createBitmap(mStartMoveItemView 
          .getDrawingCache()); 
      //       ,      ,          
      mStartMoveItemView.destroyDrawingCache(); 
      break; 
    case MotionEvent.ACTION_MOVE: 
      mMoveX = (int) ev.getX(); 
      mMoveY = (int) ev.getY(); 
      //         item    ,     item         mRunnable 
      //       longClick 
      if (!isTouchInItem(mStartMoveItemView, mMoveX, mMoveY)) { 
        mHandler.removeCallbacks(mLongClickRunnable); 
      } 
      // //  Gridview      ,              
      if (isMove) { 
        onDragItem(mMoveX, mMoveY); 
        return true; 
      } 
      break; 
    case MotionEvent.ACTION_UP: 
      mUpX = (int) ev.getX(); 
      mUpY = (int) ev.getY(); 
      mHandler.removeCallbacks(mLongClickRunnable); 
      if(isMove){ 
        deleteIfNeed(); 
      } 
      removeDragImage(); 
      isMove = false; 
      break; 
    default: 
      break; 
    } 
    return super.onTouchEvent(ev); 
  } 
  /** 
   *        ,       
   */ 
  private void deleteIfNeed() { 
    int y = mUpY - mPoint2ItemTop + mOffset2Top 
        - mStatusHeight; 
    if(y<50){ 
      if(mUninstallListener!=null) 
      mUninstallListener.onUninstallListener(mMovePosition); 
    } 
  } 
  /** 
   *      GridView item   
   * 
   * @param itemView 
   * @param x 
   * @param y 
   * @return 
   */ 
  private boolean isTouchInItem(View dragView, int x, int y) { 
    if (dragView == null) { 
      return false; 
    } 
    int leftOffset = dragView.getLeft(); 
    int topOffset = dragView.getTop(); 
    if (x < leftOffset || x > leftOffset + dragView.getWidth()) { 
      return false; 
    } 
    if (y < topOffset || y > topOffset + dragView.getHeight()) { 
      return false; 
    } 
    return true; 
  } 
  /** 
   *         
   * 
   * @param bitmap 
   * @param downX 
   *                X   
   * @param downY 
   *                X   
   */ 
  private void createDragImage(Bitmap bitmap, int downX, int downY) { 
    mWindowLayoutParams = new WindowManager.LayoutParams(); 
    mWindowLayoutParams.format = PixelFormat.TRANSLUCENT; //             
    mWindowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT; 
    mWindowLayoutParams.x = downX - mPoint2ItemLeft + mOffset2Left; 
    mWindowLayoutParams.y = downY - mPoint2ItemTop + mOffset2Top 
        - mStatusHeight; 
    mWindowLayoutParams.alpha = 0.55f; //     
    mWindowLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT; 
    mWindowLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; 
    mWindowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 
        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 
    mMoveImageView = new ImageView(getContext()); 
    mMoveImageView.setImageBitmap(bitmap); 
    mWindowManager.addView(mMoveImageView, mWindowLayoutParams); 
  } 
  /** 
   *             
   */ 
  private void removeDragImage() { 
    if (mMoveImageView != null) { 
      mWindowManager.removeView(mMoveImageView); 
      mMoveImageView = null; 
    } 
  } 
  /** 
   *   item,      item       ,item       GridView      
   * 
   * @param x 
   * @param y 
   */ 
  private void onDragItem(int moveX, int moveY) { 
    mWindowLayoutParams.x = moveX - mPoint2ItemLeft + mOffset2Left; 
    mWindowLayoutParams.y = moveY - mPoint2ItemTop + mOffset2Top 
        - mStatusHeight; 
    mWindowManager.updateViewLayout(mMoveImageView, mWindowLayoutParams); //         
  } 
  /** 
   *          
   * 
   * @param context 
   * @return 
   */ 
  private static int getStatusHeight(Context context) { 
    int statusHeight = 0; 
    Rect localRect = new Rect(); 
    ((Activity) context).getWindow().getDecorView() 
        .getWindowVisibleDisplayFrame(localRect); 
    statusHeight = localRect.top; 
    if (0 == statusHeight) { 
      Class<?> localClass; 
      try { 
        localClass = Class.forName("com.android.internal.R$dimen"); 
        Object localObject = localClass.newInstance(); 
        int i5 = Integer.parseInt(localClass 
            .getField("status_bar_height").get(localObject) 
            .toString()); 
        statusHeight = context.getResources().getDimensionPixelSize(i5); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
    return statusHeight; 
  } 
  /** 
   *           ,   1000   
   * 
   * @param responseMS 
   */ 
  public void setResponseMS(long responseMS) { 
    this.responseMS = responseMS; 
  } 
  /** 
   *           ,   1000   
   * 
   * @param responseMS 
   */ 
  public void setVibrator(long vibratorMs) { 
    this.vibratorMs = vibratorMs; 
  } 
  public void setOnUninstallListener(UninstallListener l){ 
    mUninstallListener=l; 
  }; 
  private UninstallListener mUninstallListener; 
} 
MainActivity.java

package com.example.gridviewmovedemo; 
import java.util.ArrayList; 
import java.util.HashMap; 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemLongClickListener; 
import android.widget.SimpleAdapter; 
import com.leafact.GridView.MoveGridView; 
import com.leafact.GridView.UninstallListener; 
public class MainActivity extends Activity { 
  private MoveGridView mMoveGridView; 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    mMoveGridView = (MoveGridView) findViewById(R.id.gridview); 
    final ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>(); 
    for (int i = 0; i < 10; i++) { 
      HashMap<String, Object> map = new HashMap<String, Object>(); 
      map.put("ItemText", "NO." + String.valueOf(i));//     ItemText 
      lstImageItem.add(map); 
    } 
    final SimpleAdapter saImageItems = new SimpleAdapter(this, 
        lstImageItem,//      
        R.layout.gridview_item, 
        //      ImageItem      
        new String[] { "ItemText" }, 
        // ImageItem XML       ImageView,  TextView ID 
        new int[] { R.id.ItemText }); 
    //        
    mMoveGridView.setAdapter(saImageItems); 
    //          
    mMoveGridView.setOnUninstallListener(new UninstallListener() { 
      @Override 
      public void onUninstallListener(int position) { 
        lstImageItem.remove(position); 
        saImageItems.notifyDataSetChanged(); 
      } 
    }); 
  } 
  @Override 
  public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
  } 
} 
UninstallListener.java

package com.leafact.GridView; 
public interface UninstallListener { 
  void onUninstallListener(int position); 
} 
activity_main.xml

<LinearLayout 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" 
  android:background="#fff" 
  android:orientation="vertical" 
  tools:context=".MainActivity" > 
  <RelativeLayout 
    android:layout_width="fill_parent" 
    android:layout_height="100dip" 
    android:background="#ccc" > 
    <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="fill_parent" 
      android:layout_centerHorizontal="true" 
      android:gravity="center" 
      android:text="  " 
      android:textColor="#fff" 
      android:textSize="28sp" /> 
  </RelativeLayout> 
  <com.leafact.GridView.MoveGridView 
    android:id="@+id/gridview" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:horizontalSpacing="5dip" 
    android:numColumns="3" 
    android:verticalSpacing="5dip" /> 
</LinearLayout> 
gridview_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:background="#2248DD" > 
  <TextView 
    android:id="@+id/ItemText" 
    android:layout_width="wrap_content" 
    android:layout_height="100dip" 
    android:layout_centerHorizontal="true" 
    android:gravity="center" > 
  </TextView> 
</RelativeLayout> 
총결산
위 에서 말 한 것 은 편집장 이 소개 한 안 드 로 이 드 가 드래그 가능 한 GridView 효 과 를 실현 하 는 것 입 니 다.드래그 가능 한 데이터 원본 을 길 게 누 르 고 삭제 하 는 데 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.편집장 은 신속하게 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기