Android custom Viewgroup switching View with Adsorption Effect

Source: Internet
Author: User

Android custom Viewgroup switching View with Adsorption Effect

 

1. Overview first

This is probably the result. Let's talk about the implementation Idea 1 first. first, we need to get the image url (network), id, path (local), bind the View with the data, and write our own Adapter 2. customize the layout of the view to be displayed in the Viewgroup, and process the touch event logically. 3. write switch callback
2. Implementation 1) custom Adapter the network image I downloaded here can also put the image under res to set the ImageView content
Public class DragPageViewAdapter {private static final String TAG = DragPageViewAdapter; private List
 
  
MDatas; private Context mContext; private LayoutInflater inflater;/*** width and height */int width; int height; public DragPageViewAdapter (Context mContext) {this. mContext = mContext; inflater = LayoutInflater. from (mContext); width = (int) (0.8 * DragViewActivity. mScreenWidth); // The width is 0.8 height = (int) (0.8 * DragViewActivity. mScreenWidth);} public int getCount () {return mDatas = null? 0: mDatas. size ();} public int getItemId (int position) {return position;} public Object getItem (int position) {return mDatas = null? Null: mDatas. get (position);} public View getView (int position, View convertView, ViewGroup parent) {LogHelper. d (TAG, position: + position); final ImageView imageView = new ImageView (mContext); RelativeLayout. layoutParams params = new RelativeLayout. layoutParams (width, height); params. addRule (Gravity. CENTER); imageView. setLayoutParams (params); imageView. setBackgroundDrawable (mContext. getResources (). GetDrawable (R. drawable. gray_border); ViewHelper. setAlpha (imageView, 1.0f); String url = mDatas. get (position). getPictureUrl (); if (! Utils. stringIsNull (url) {url = url. substring (0, url. lastIndexOf (.)) + --300x300.png; // UILHelper. loadImageUrl (url, imageView, 0); UILHelper. loadImageUrl (url, new SimpleImageLoadingListener () {@ Override public void onLoadingComplete (String imageUri, View view, Bitmap loadedImage) {imageView. setImageBitmap (loadedImage) ;}}) ;}convertview = imageView; convertView. setTag (mDatas. get (position); // viewHolder. mImageView. setImageResource (Integer) mDatas. get (position); return convertView;} public void setData (List data) {mDatas = data;} private class ViewHolder {ImageView mImageView ;}}
 

Use this Adapter to download the desired image repository network. When necessary, the ImageView will request the download. And bind the data to the ImageView through the setTag method. 2) use the custom Viewgroup to directly add the code. What we need to do is. the onMeasure method measures the sub-user and sub-view B. the onLayout method is used to layout the child view. c. onTouchEvent processes the touch event and determines whether to switch to the next view when it is up. If not, use the property animation to restore the view State to d. binding and switching callback e. after switching, remove the current View from viewgruop, add a view to be loaded, and assign the current view to the switched view to ensure that the viewgroup contains no more than the specified number of sub-views, disable OOM
Public class DragPageView extends ViewGroup {private static final String TAG = DragPageView;/*** adapter */private DragPageViewAdapter mAdapter;/*** number of views */private int ONE_SCREEN_COUNT = 2; /*** screen width and height */private int mScrenWidth; private int mScreenHeight;/*** width and height of sub-elements */private int mChildWidth; private int mChildHeight; /*** index of the current last image */private int mLastIndex;/***** subscript of the current first image */private int mFirstIndex; /*** current display View */private View mFirstView;/* x y */private int mDownX; private int mDownY; /*** x y */private int mCurX; private int mCurY; public static int mDirection =-1; public static final int DIRECTION_LEFT_TO_RIGHT = 1; public static final int DIRECTION_RIGHT_TO_LEFT = 2;/*** Save the View and position key-value pairs */private Map
 
  
MViewMap = new HashMap
  
   
();/*** Maximum Rotation Angle */private int ROTATE_DEGREE = 30; private int CHILD_OFFSET = 10;/*** save callback interface */private OnImageSavedListener mOnImageSavedListener; public void setOnImageSavedListener (OnImageSavedListener mOnImageSavedListener) {this. mOnImageSavedListener = mOnImageSavedListener;} public DragPageView (Context context) {this (context, null);} public DragPageView (Context context, AttributeSet Trs) {this (context, attrs, 0);} public DragPageView (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr ); // obtain the screen width and high WindowManager windowManager = (WindowManager) context. getSystemService (Context. WINDOW_SERVICE); DisplayMetrics metrics = new DisplayMetrics (); windowManager. getdefadisplay display (). getMetrics (metrics); mScrenWidth = metrics. widthPixels; mScreenHe Ight = metrics. heightPixels ;}@ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {/*** get the width and height that the ViewGroup superior container recommends for it, and the calculation mode */int widthMode = MeasureSpec. getMode (widthMeasureSpec); int heightMode = MeasureSpec. getMode (heightMeasureSpec); int sizeWidth = MeasureSpec. getSize (widthMeasureSpec); int sizeHeight = MeasureSpec. getSize (heightMeasureSpec); // calculate the width and height of all childView S. MeasureChildren (widthMeasureSpec, heightMeasureSpec); setMeasuredDimension (mScrenWidth, sizeHeight);} @ Override protected void onLayout (boolean changed, int l, int t, int r, int B) {for (int I = 0; I <getChildCount (); I ++) {View child = getChildAt (I); mChildWidth = child. getMeasuredWidth (); mChildHeight = child. getMeasuredHeight (); int left = getWidth ()/2-mChildWidth/2; int top = getHeight ()/2 -MChildHeight * 2/3; int right = left + mChildWidth; int bottom = top + mChildHeight; if (I = 0) child. layout (left + CHILD_OFFSET, top + CHILD_OFFSET, right + CHILD_OFFSET, bottom + CHILD_OFFSET); else child. layout (left, top, right, bottom) ;}} public void initDatas (DragPageViewAdapter mAdapter) {this. mAdapter = mAdapter; initView () ;}@ TargetApi (Build. VERSION_CODES.HONEYCOMB) private void initView () {r EmoveAllViews (); for (int I = 0; I <ONE_SCREEN_COUNT; I ++) {View view = mAdapter. getView (I, null, this); mViewMap. put (I, view);} // Add the view flashback stored in the mViewMap TO THE ViewGroup, because the ViewGroup index = 0 is at the bottom layer for (int j = ONE_SCREEN_COUNT-1; j> = 0; j --) {addView (mViewMap. get (j); if (j = 0) {mFirstView = mViewMap. get (j) ;}} mLastIndex = ONE_SCREEN_COUNT-1; mFirstIndex = mLastIndex-ONE_SCREEN_COUNT-1;} @ TargetApi (Build. VERSION_CODES.HONEYCOMB) @ Override public boolean onTouchEvent (MotionEvent event) {int focusX = (int) event. getX (); int focusY = (int) event. getY (); switch (event. getAction () {case MotionEvent. ACTION_DOWN: mDownX = mCurX = focusX; mDownY = mCurY = focusY; break; case MotionEvent. ACTION_MOVE: final int deltaX = focusX-mCurX; final int deltaY = focusY-mCurY; if (Math. abs (deltaX)> 5 | Ma Th. abs (deltaY)> 5) {if (focusX> mDownX) {mDirection = DIRECTION_LEFT_TO_RIGHT;} else {mDirection = direction;} handlerScroll (deltaX, deltaY); // mFirstView. setmediatx (float) (mFirstView. getMeasuredWidth () * 0.5); // mFirstView. setpolicty (mFirstView. getMeasuredHeight (); mFirstView. setRotation (ROTATE_DEGREE * (focusX-mDownX)/mChildWidth);} mCurX = focusX; mCurY = focusY; break; case Moti OnEvent. ACTION_UP: LogHelper. d (TAG, mPreX: + mDownX + mPreY + mDownY + mCurX: + mCurX + mCurY: + mCurY); if (Math. abs (mCurX-mDownX)> mChildWidth/2 & mLastIndex <mAdapter. getCount () {loadNextImage () ;}else {resetView () ;}break ;}return true ;} private void resetView () {PropertyValuesHolder oaX = PropertyValuesHolder. ofFloat (translationX, 0); PropertyValuesHolder oaY = PropertyValuesHolder. OfFloat (translationY, 0); PropertyValuesHolder rotate = PropertyValuesHolder. ofFloat (rotation, 0); ObjectAnimator. ofPropertyValuesHolder (mFirstView, oaX, oaY, rotate ). start ();} public void loadNextImage () {ObjectAnimator oaX = null; ObjectAnimator oaRotate = null; if (mLastIndex = mAdapter. getCount () return; if (mDirection = DIRECTION_LEFT_TO_RIGHT) {oaX = new ObjectAnimator (). ofFloat (mFirstVi Ew, translationX, 800); oaRotate = new ObjectAnimator (). ofFloat (mFirstView, rotation, ROTATE_DEGREE); // notification callback saved view if (mOnImageSavedListener! = Null) {mOnImageSavedListener. onImageSaved (mFirstView) ;}} else {oaX = new ObjectAnimator (). ofFloat (mFirstView, translationX,-800); oaRotate = new ObjectAnimator (). ofFloat (mFirstView, rotation,-ROTATE_DEGREE); if (mOnImageSavedListener! = Null) {mOnImageSavedListener. onImageDelete (mFirstView) ;}} oaX. addListener (new AnimatorListenerAdapter () {@ Override public void onAnimationEnd (Animator animation) {// load the next image mViewMap after the animation ends. remove (mFirstIndex); // Delete view removeAllViews (); // obtain the next image if (mLastIndex + 1)> = mAdapter. getCount () {addView (mViewMap. get (mLastIndex);} else {View view = mAdapter. getView (++ mLastIndex, null, DragPageView. this); mViewMap. put (mLastIndex, view); addView (mViewMap. get (mLastIndex); addView (mViewMap. get (mLastIndex-1); mFirstView = mViewMap. get (mLastIndex-1) ;}}); // enable the animation oaRotate. start (); oaX. start () ;}@ TargetApi (Build. VERSION_CODES.HONEYCOMB) private void handlerScroll (float distanceX, float distanceY) {int newLeft = (int) (mFirstView. getLeft () + distanceX); int newTop = (int) (mFirstView. getTop () + distanceY); float [] deltaVector = {distanceX, distanceY}; mFirstView. getMatrix (). mapVectors (deltaVector); mFirstView. setTranslationX (mFirstView. getTranslationX () + deltaVector [0]); mFirstView. setTranslationY (mFirstView. getTranslationY () + deltaVector [1]);} public interface OnImageSavedListener {public void onImageSaved (View view); public void onImageDelete (View view );}}
  
 
3) Events of Activity a. Request data initialization Adapter and ViewGroup B. Switch callback response c. click the button to switch events
Public class DragViewActivity extends BaseActivity {private static final String TAG = DragViewActivity; private DragPageViewAdapter adapter; private DragPageView mDragView; private int pageIndex = 1; private int pageSize = 21; private int total; /*** userId */private String userId; // private List of network request data
 
  
Lists; // private List of saved view information
  
   
MSavedView; private WxCollocationRandomList mViewInfo;/*** screen width and height */public static int mScreenWidth; public static int mScreenHeight; private TextView mSkip; private TextView mSave; private TextView mDone; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. dragview_act); WindowManager windowManager = (WindowManager) getSystemService (WINDOW_SERVICE); DisplayMetrics displayMetrics = new DisplayMetrics (); windowManager. getdefadisplay display (). getMetrics (displayMetrics); mScreenWidth = displayMetrics. widthPixels; mScreenHeight = displayMetrics. heightPixels; userId = SettingsManager. getSettingsManager (this ). getUserId (); initView (); httpgtimageinfo (pageIndex);} private void httpgtimageinfo (final int pageIndex) {JSONObject object = new JSONObject (); try {object. put (pageIndex, pageIndex); object. put (pageSize, pageSize);} catch (JSONException e) {e. printStackTrace ();} if (pageIndex = 1) {showProgress (getResources (). getString (R. string. app_data_loading);} HttpsRequestUtil. doHttpsVolleyPost (this, SOAServices. COLLOCATION_SERVICE, SOAMethods. RANDOM_COLLOCATION, HttpsRequestUtil. GET, object, new Response. listener
   
    
() {@ Override public void onResponse (String response) {if (pageIndex = 1) {closeProgress () ;}transformdata (response) ;}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError error) {closeProgress () ;}}/*** request data, initialize the adapter and Viewgroup * @ param response */private void transformData (String response) {Gson gson = new Gson (); WxCollocationRandomFilter wxCollocationRandomFilter = gson. fromJson (response, WxCollocationRandomFilter. class); total = wxCollocationRandomFilter. getTotal (); if (total = 0) return; lists = wxCollocationRandomFilter. getCollocationRandomLists (); adapter. setData (lists); mDragView. initDatas (adapter);} private void initView () {mDragView = (DragPageView) findViewById (R. id. dragView); adapter = new DragPageViewAdapter (this); mDragView. setOnImageSavedListener (new DragPageView. onImageSavedListener () {@ Override public void onImageSaved (View view) {mViewInfo = (WxCollocationRandomList) view. getTag (); httpSaveFavorite (mViewInfo) ;}@ Override public void onImageDelete (View view) {mViewInfo = (WxCollocationRandomList) view. getTag (); httpDeleteFavorite (mViewInfo) ;}}); mSkip = (TextView) findViewById (R. id. skip); mSave = (TextView) findViewById (R. id. save); mDone = (TextView) findViewById (R. id. done); mSkip. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {mDragView. mDirection = mDragView. DIRECTION_RIGHT_TO_LEFT; mDragView. loadNextImage () ;}}); mSave. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {mDragView. mDirection = mDragView. DIRECTION_LEFT_TO_RIGHT; mDragView. loadNextImage () ;}}); mDone. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {DragViewActivity. this. finish () ;}});}/*** like * @ param mViewInfo with information sourcE_TYPE 1 product 2 with */private void httpSaveFavorite (WxCollocationRandomList mViewInfo) {JSONObject jsonObject = new JSONObject (); try {jsonObject. put (sourcE_ID, mViewInfo. getId (); jsonObject. put (userId, userId); jsonObject. put (creatE_USER, mViewInfo. getCreateUser (); jsonObject. put (sourcE_TYPE, 2);} catch (JSONException e) {e. printStackTrace ();} HttpsRequestUtil. doHttpsVolleyPost (DragViewActivity. this, SOAServices. ORDER_SERVICE, SOAMethods. FAVORITE_ADD, HttpsRequestUtil. POST, jsonObject, new Response. listener
    
     
() {@ Override public void onResponse (String response) {LogHelper. d (TAG, SaveFavorite Success !); }, New Response. ErrorListener () {@ Override public void onErrorResponse (VolleyError error) {LogHelper. d (TAG, SaveFavorite Error !); });}/*** Delete @ param mViewInfo with information sourcE_TYPE 1 product 2 with */private void httpDeleteFavorite (custom mViewInfo) {JSONObject jsonObject = new JSONObject (); try {jsonObject. put (sourcE_ID, mViewInfo. getId (); jsonObject. put (userId, userId); jsonObject. put (creatE_USER, mViewInfo. getCreateUser (); jsonObject. put (sourcE_TYPE, 2);} catch (JSONException e) {e. printStackTrace ();} HttpsRequestUtil. doHttpsVolleyPost (DragViewActivity. this, SOAServices. ORDER_SERVICE, SOAMethods. FAVORITE_DELETE, HttpsRequestUtil. POST, jsonObject, new Response. listener
     
      
() {@ Override public void onResponse (String response) {LogHelper. d (TAG, DeleteFavorite Success !); }, New Response. ErrorListener () {@ Override public void onErrorResponse (VolleyError error) {LogHelper. d (TAG, DeleteFavorite Error !); }});}}
     
    
   
  
 



 

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.