• Android viewpager 嵌套 viewpager滑动 点击事件冲突解决方案


    为了解决这个问题。可以自定义viewpager,然后在里面监听首饰,自定义点击事件

    package com.hpuvoice.view;
    
    import android.content.Context;
    import android.graphics.PointF;
    import android.support.v4.view.ViewPager;
    import android.util.AttributeSet;
    import android.view.GestureDetector;
    import android.view.GestureDetector.OnGestureListener;
    import android.view.MotionEvent;
    
    public class MyViewPager extends ViewPager implements OnGestureListener {
    
    	/** 手势滑动处理类 **/
    	private GestureDetector mDetector;
    	/** 触摸时按下的点 **/
    	PointF downP = new PointF();
    	/** 触摸时当前的点 **/
    	PointF curP = new PointF();
    
    	OnSingleTouchListener onSingleTouchListener;
    
    	public MyViewPager(Context context, AttributeSet attrs) {
    		super(context, attrs);
    		GestureDetector detector = new GestureDetector(context, this);
    		mDetector = detector;
    	}
    
    	public GestureDetector getGestureDetector() {
    		return mDetector;
    	}
    
    	@Override
    	public boolean onTouchEvent(MotionEvent arg0) {
    		curP.x = arg0.getX();
    		curP.y = arg0.getY();
    		getParent().requestDisallowInterceptTouchEvent(true);
    		if (arg0.getAction() == MotionEvent.ACTION_DOWN) {
    			downP.x = arg0.getX();
    			downP.y = arg0.getY();
    		}
    
    		if (arg0.getAction() == MotionEvent.ACTION_MOVE) {
    			// 此句代码是为了通知他的父ViewPager现在进行的是本控件的操作,不要对我的操作进行干扰
    			getParent().requestDisallowInterceptTouchEvent(true);
    		}
    
    		if (arg0.getAction() == MotionEvent.ACTION_UP) {
    			// 在up时判断是否按下和松手的坐标为一个点
    			// 如果是一个点,将执行点击事件,这是我自己写的点击事件,而不是onclick
    			if ((downP.x == curP.x) && (downP.y == curP.y)) {
    				onSingleTouch();
    				return true;
    			}
    		}
    
    		return super.onTouchEvent(arg0);
    	}
    
    	@Override
    	public void setOnPageChangeListener(OnPageChangeListener listener) {
    		super.setOnPageChangeListener(listener);
    	}
    
    	/**
    	 * 单击   
    	 */
    	public void onSingleTouch() {
    		if (onSingleTouchListener != null) {
    			onSingleTouchListener.onSingleTouch();
    		}
    	}
    
    	/**
    	 *    * 创建点击事件接口    *   
    	 */
    	public interface OnSingleTouchListener {
    		public void onSingleTouch();
    	}
    
    	public void setOnSingleTouchListener(
    			OnSingleTouchListener onSingleTouchListener) {
    		this.onSingleTouchListener = onSingleTouchListener;
    	}
    
    	@Override
    	public boolean onDown(MotionEvent e) {
    		return false;
    	}
    
    	@Override
    	public void onShowPress(MotionEvent e) {
    
    	}
    
    	@Override
    	public boolean onSingleTapUp(MotionEvent e) {
    		return false;
    	}
    
    	@Override
    	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
    			float distanceY) {
    		return false;
    	}
    
    	@Override
    	public void onLongPress(MotionEvent e) {
    
    	}
    
    	@Override
    	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    			float velocityY) {
    		return false;
    	}
    
    }
    

      然后在使用该viewpager的类中,进行一系列监听,使用,同事本案例是为了展示首页轮播图的效果,其中另外一个点就是首页轮播图动态添加小圆点。并且实现轮播效果。

    package com.hpuvoice.fragment;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Timer;
    import java.util.TimerTask;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.annotation.SuppressLint;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.support.v4.view.PagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v4.view.ViewPager.OnPageChangeListener;
    import android.util.TypedValue;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.view.animation.Animation;
    import android.view.animation.Animation.AnimationListener;
    import android.view.animation.AnimationUtils;
    import android.widget.Button;
    import android.widget.GridView;
    import android.widget.ImageView;
    import android.widget.ImageView.ScaleType;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import com.edaixi.activity.CityListActivity;
    import com.edaixi.activity.LoginActivity;
    import com.edaixi.activity.MainActivity;
    import com.edaixi.activity.PlaceorderActivity;
    import com.edaixi.activity.R;
    import com.edaixi.activity.WebActivity;
    import com.edaixi.appdata.Kclassdata;
    import com.edaixi.appdata.KeepingData;
    import com.edaixi.bean.Bannerlistbean;
    import com.edaixi.bean.InappUrlbean;
    import com.edaixi.bean.PostCommonBean;
    import com.edaixi.listadpter.Myfuncadpter;
    import com.edaixi.utils.Common;
    import com.edaixi.utils.DensityUtil;
    import com.edaixi.utils.NetUtil;
    import com.edaixi.utils.SaveUtils;
    import com.edaixi.view.MySpringRing;
    import com.edaixi.view.MyViewPager.OnSingleTouchListener;
    import com.google.gson.Gson;
    import com.lidroid.xutils.BitmapUtils;
    
    public class HomeFragment extends BaseFragment implements OnClickListener {
    	private static final int GETBANNERFAILD = 2;
    	private static final int GETBANNERSUCCED = 3;
    	private static final int GETFUNCTIONBTNSUCCED = 4;
    	private static final int GETFUNCTIONBTNFAILD = 5;
    	boolean RequstFlag = false;
    	private View view;
    	private Button main_order_btn;
    	private HashMap<String, String> parms;
    	private SaveUtils saveUtils;
    	private String address = "";
    	private GridView main_grid;
    	private Myfuncadpter adapter;
    	private com.edaixi.view.MyViewPager myview_pager;
    	private ImageView anim_trousers;
    	private ImageView anim_womencloth;
    	private ImageView anim_clothsmall;
    	private ImageView imageView_title;
    	private ArrayList<Bannerlistbean> funditonlist;
    	private JSONObject str;
    	private TitleAdapter title;
    	private Animation tosmallanimation;
    	private ImageView anim_sleeveshort;
    	private ArrayList<Bannerlistbean> banerlistbak;
    	private LinearLayout pager_bottom;
    	private int Animorder;
    	private MySpringRing cricleView;
    	private ImageView point;
    	private static TextView loction_text;
    	private int currentPosition = 0;
    	private boolean is_Loop_Flag = true;;
    
    	@SuppressLint("HandlerLeak")
    	private Handler handler = new Handler() {
    		private Gson gson = new Gson();
    
    		@Override
    		public void handleMessage(Message msg) {
    			myview_pager.setCurrentItem(currentPosition);
    			currentPosition++;
    			if ((banerlistbak.size() > 0)
    					&& (currentPosition > banerlistbak.size() - 1)) {
    				currentPosition = (currentPosition % banerlistbak.size());
    			}
    			if (is_Loop_Flag) {
    				handler.sendEmptyMessageDelayed(0, 3000);
    			}
    			try {
    				switch (msg.what) {
    				case GETBANNERSUCCED:
    					PostCommonBean jsonCommonBean = gson.fromJson(
    							(String) msg.obj, PostCommonBean.class);
    					if (jsonCommonBean.isRet()) {
    						String data = jsonCommonBean.getData();
    						banerlistbak = null;
    						banerlistbak = new ArrayList<Bannerlistbean>();
    						paserbaner(data, banerlistbak);
    						myview_pager.setCurrentItem(0);
    						currentPosition = Integer.MAX_VALUE / 2
    								- (Integer.MAX_VALUE / 2 % banerlistbak.size());
    						addBannerPoint();
    						TitleAdapter titlebak = new TitleAdapter(banerlistbak);
    						myview_pager.setAdapter(titlebak);
    						titlebak.notifyDataSetChanged();
    					}
    					break;
    				case GETBANNERFAILD:
    					break;
    				case GETFUNCTIONBTNSUCCED:
    					RequstFlag = true;
    					PostCommonBean CommonBean = gson.fromJson((String) msg.obj,
    							PostCommonBean.class);
    					if (CommonBean.isRet()) {
    						String data = CommonBean.getData();
    						paserbaner(data, funditonlist);
    						adapter.notifyDataSetChanged();
    					}
    					break;
    				case GETFUNCTIONBTNFAILD:
    					break;
    				}
    				super.handleMessage(msg);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    	};
    
    	@SuppressLint("HandlerLeak")
    	@Override
    	public View onCreateView(LayoutInflater inflater, ViewGroup container,
    			Bundle savedInstanceState) {
    		view = (LinearLayout) inflater.inflate(R.layout.fragment_home,
    				container, false);
    		main_order_btn = (Button) view.findViewById(R.id.main_order_btn);
    		main_grid = (GridView) view.findViewById(R.id.main_grid);
    		myview_pager = (com.edaixi.view.MyViewPager) view
    				.findViewById(R.id.myview_pager);
    		cricleView = (MySpringRing) view.findViewById(R.id.myring_circle);
    		cricleView.startAnim();
    		pager_bottom = (LinearLayout) view.findViewById(R.id.pager_bottom);
    		anim_trousers = (ImageView) view.findViewById(R.id.anim_trousers);
    		anim_womencloth = (ImageView) view.findViewById(R.id.anim_womencloth);
    		anim_clothsmall = (ImageView) view.findViewById(R.id.anim_clothsmall);
    		anim_sleeveshort = (ImageView) view.findViewById(R.id.anim_sleeveshort);
    		loction_text = (TextView) view.findViewById(R.id.loction_text);
    		loction_text.setOnClickListener(this);
    
    		myview_pager.setCurrentItem(currentPosition);
    		myview_pager.setOnPageChangeListener(new OnPageChangeListener() {
    			@Override
    			public void onPageSelected(int position) {
    				currentPosition = position;
    				if (pager_bottom.getChildCount() > 0) {
    					for (int i = 0; i < banerlistbak.size(); i++) {
    						pager_bottom.getChildAt(i).setBackgroundResource(
    								getImageResIDs()[0]);
    					}
    					pager_bottom.getChildAt(position).setBackgroundResource(
    							getImageResIDs()[1]);
    				}
    			}
    
    			@Override
    			public void onPageScrollStateChanged(int arg0) {
    			}
    
    			@Override
    			public void onPageScrolled(int arg0, float arg1, int arg2) {
    			}
    		});
    
    		myview_pager.setOnSingleTouchListener(new OnSingleTouchListener() {
    
    			@Override
    			public void onSingleTouch() {
    				Intent intent = new Intent();
    				if (banerlistbak.get(myview_pager.getCurrentItem())
    						.getUrl_type().equals("web")) {
    					intent.putExtra("bannerlistbean",
    							banerlistbak.get(myview_pager.getCurrentItem()));
    					intent.setClass(getActivity(), WebActivity.class);
    					startActivity(intent);
    				} else if (banerlistbak.get(myview_pager.getCurrentItem())
    						.getUrl_type().equals("in_app")) {
    					if (!saveUtils.getBoolSP(KeepingData.LOGINED)) {
    						intent.setClass(getActivity(), LoginActivity.class);
    					} else {
    						Gson gson = new Gson();
    						InappUrlbean inappurlbean = gson.fromJson(banerlistbak
    								.get(myview_pager.getCurrentItem()).getUrl(),
    								InappUrlbean.class);
    						intent.setClass(getActivity(), Kclassdata
    								.getRechageclsss(inappurlbean.getKlass()));
    					}
    					startActivity(intent);
    				}
    			}
    		});
    		initView();
    		handler.sendEmptyMessageDelayed(0, 3000);
    		return view;
    	}
    
    	private void startanim() {
    		tosmallanimation = (Animation) AnimationUtils.loadAnimation(
    				getActivity(), R.anim.main_btn_scal_big);
    		main_order_btn.startAnimation(tosmallanimation);
    	}
    
    	public static TextView getloctionview() {
    		return loction_text;
    	}
    
    	private void get_func_button_list() {
    		parms.clear();
    		parms.put("width",
    				String.valueOf(DensityUtil.getWidthInPx(getActivity())));
    		parms.put("height",
    				String.valueOf(DensityUtil.getHeightInPx(getActivity())));
    		if (saveUtils.getStrSP(KeepingData.User_City_Id) != null) {
    			parms.put("city_id", saveUtils.getStrSP(KeepingData.User_City_Id));
    		} else {
    			parms.put("city_id", "1");
    		}
    		((MainActivity) getActivity()).getdate(parms,
    				Common.GET_FUNC_BUTTON_LIST, handler, GETFUNCTIONBTNSUCCED,
    				GETFUNCTIONBTNFAILD, false, true, false);
    	}
    
    	private void get_banner_list() {
    		parms.clear();
    		parms.put("width",
    				String.valueOf(DensityUtil.getWidthInPx(getActivity())));
    		parms.put("height",
    				String.valueOf(DensityUtil.getHeightInPx(getActivity())));
    		if (saveUtils.getStrSP(KeepingData.User_City_Id) != null) {
    			parms.put("city_id", saveUtils.getStrSP(KeepingData.User_City_Id));
    		} else {
    			parms.put("city_id", "1");
    		}
    		((MainActivity) getActivity()).getdate(parms, Common.GET_BANNER_LIST,
    				handler, GETBANNERSUCCED, GETBANNERFAILD, true, true, false);
    
    	}
    
    	private void initView() {
    		banerlistbak = new ArrayList<Bannerlistbean>();
    		funditonlist = new ArrayList<Bannerlistbean>();
    		saveUtils = new SaveUtils(this.getActivity());
    		parms = new HashMap<String, String>();
    		get_banner_list();
    		title = new TitleAdapter(banerlistbak);
    		myview_pager.setAdapter(title);
    		adapter = new Myfuncadpter(getActivity(), funditonlist);
    		main_grid.setAdapter(adapter);
    		get_func_button_list();
    		Animation toleftanim = (Animation) AnimationUtils.loadAnimation(
    				getActivity(), R.anim.toleft_translaneannim);
    		final Animation torightanim = (Animation) AnimationUtils.loadAnimation(
    				getActivity(), R.anim.toright_translateanim);
    		final Animation torightanim1 = (Animation) AnimationUtils
    				.loadAnimation(getActivity(), R.anim.toleft_translation);
    		final Animation toleftanim1 = (Animation) AnimationUtils.loadAnimation(
    				getActivity(), R.anim.long_short_anim);
    		AnimationListener animationListener = new AnimationListener() {
    			@Override
    			public void onAnimationStart(Animation animation) {
    			}
    
    			@Override
    			public void onAnimationRepeat(Animation animation) {
    
    			}
    
    			@Override
    			public void onAnimationEnd(Animation animation) {
    				Animorder++;
    				switch (Animorder) {
    				case 1:
    					anim_womencloth.startAnimation(torightanim);
    					break;
    				case 2:
    					anim_clothsmall.startAnimation(torightanim1);
    					break;
    				case 3:
    					anim_sleeveshort.startAnimation(toleftanim1);
    					break;
    				default:
    					break;
    				}
    			}
    		};
    		anim_trousers.setVisibility(View.VISIBLE);
    		anim_womencloth.setVisibility(View.VISIBLE);
    		anim_clothsmall.setVisibility(View.VISIBLE);
    		anim_sleeveshort.setVisibility(View.VISIBLE);
    		anim_trousers.startAnimation(toleftanim);
    		toleftanim.setAnimationListener(animationListener);
    		torightanim.setAnimationListener(animationListener);
    		torightanim1.setAnimationListener(animationListener);
    		toleftanim1.setAnimationListener(animationListener);
    		main_order_btn.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				startanim();
    				tosmallanimation.setAnimationListener(new AnimationListener() {
    
    					@Override
    					public void onAnimationStart(Animation animation) {
    					}
    
    					@Override
    					public void onAnimationRepeat(Animation animation) {
    					}
    
    					@Override
    					public void onAnimationEnd(Animation animation) {
    
    						if (!saveUtils.getBoolSP(KeepingData.LOGINED)) {
    							startActivity(new Intent(getActivity(),
    									LoginActivity.class));
    							return;
    						}
    						;
    						Intent intent = new Intent(getActivity(),
    								PlaceorderActivity.class);
    						intent.putExtra("from", "fromMain");
    						intent.putExtra(KeepingData.ADDRESS_DATA, address);
    						startActivity(intent);
    					}
    				});
    
    			}
    		});
    		loction_text.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				Intent intent = new Intent(getActivity(),
    						CityListActivity.class);
    				startActivityForResult(intent, getActivity().RESULT_FIRST_USER);
    			}
    		});
    	}
    
    	@Override
    	public void setUserVisibleHint(boolean isVisibleToUser) {
    		super.setUserVisibleHint(isVisibleToUser);
    		if (isVisibleToUser) {
    			is_Loop_Flag = true;
    			handler.sendEmptyMessageDelayed(0, 3000);
    			if (NetUtil.getNetworkState(getActivity())) {
    				if ((funditonlist != null) && !RequstFlag) {
    					Timer timer = new Timer();
    					timer.schedule(new TimerTask() {
    						@Override
    						public void run() {
    							getActivity().runOnUiThread(new Runnable() {
    								@Override
    								public void run() {
    									get_banner_list();
    									get_func_button_list();
    								}
    							});
    						}
    					}, 500);
    				}
    			}
    		} else {
    			is_Loop_Flag = false;
    		}
    	}
    
    	private int[] getImageResIDs() {
    		return new int[] { R.drawable.splash_dot_default,
    				R.drawable.splash_dot_current };
    	}
    
    	private class TitleAdapter extends PagerAdapter {
    
    		private ArrayList<Bannerlistbean> mbannerlist;
    
    		public TitleAdapter(ArrayList<Bannerlistbean> bannerlist) {
    			super();
    			mbannerlist = bannerlist;
    		}
    
    		@Override
    		public int getCount() {
    			int size = mbannerlist.size() == 0 ? 2 : mbannerlist.size();
    			// if (mbannerlist.size() > 0) {
    			// return size;
    			// } else {
    			// return 2;
    			// }
    			return 3;
    		}
    
    		@Override
    		public boolean isViewFromObject(View arg0, Object arg1) {
    			return arg0 == arg1;
    		}
    
    		@Override
    		public void destroyItem(ViewGroup container, int position, Object object) {
    			((ViewPager) container).removeView((View) object);
    		}
    
    		@Override
    		public Object instantiateItem(ViewGroup container, final int position) {
    			View view = View
    					.inflate(getActivity(), R.layout.bander_title, null);
    			imageView_title = (ImageView) view
    					.findViewById(R.id.iv_bander_title);
    			imageView_title.setScaleType(ScaleType.CENTER_CROP);
    			imageView_title.setImageResource(R.drawable.banner_default);
    			if (mbannerlist.size() == 0) {
    				container.addView(view, 0);
    				return view;
    			} else {
    				BitmapUtils utils = new BitmapUtils(getActivity());
    				utils.display(imageView_title, mbannerlist.get(position)
    						.getImage_url());
    				container.addView(view, position);
    				return view;
    			}
    		}
    	}
    
    	/** 动态添加轮播图小圆点 **/
    	protected void addBannerPoint() {
    		for (int i = 0; i < banerlistbak.size(); i++) {
    			point = new ImageView(getActivity());
    			point.setBackgroundResource(R.drawable.splash_dot_current);
    
    			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    					LinearLayout.LayoutParams.WRAP_CONTENT,
    					LinearLayout.LayoutParams.WRAP_CONTENT);
    			params.gravity = Gravity.CENTER;
    			point.setLayoutParams(params);
    			point.setVisibility(View.VISIBLE);
    			if (i == 0) {
    				point.setEnabled(true);
    			} else {
    				point.setEnabled(false);
    			}
    			pager_bottom.addView(point);
    		}
    	}
    
    	/** 解析banner结果方法 **/
    	protected void paserbaner(String json, ArrayList<Bannerlistbean> bannerlist) {
    		JSONArray jsonArray;
    		bannerlist.clear();
    		try {
    			jsonArray = new JSONArray(json);
    			for (int i = 0; i < jsonArray.length(); i++) {
    				str = (JSONObject) jsonArray.opt(i);
    				Bannerlistbean bannerlistbean = new Bannerlistbean();
    				bannerlistbean.setImage_url(str.getString("image_url"));
    				bannerlistbean.setUrl_type(str.getString("url_type"));
    				bannerlistbean.setUrl(str.getString("url"));
    				bannerlistbean.setTitle(str.getString("title"));
    				if (str.getString("title").equals("按袋计费")) {
    					saveUtils.saveStrSP(KeepingData.An_Dai_Ji_Fei_Url,
    							str.getString("url"));
    				} else if (str.getString("title").equals("按件计费")) {
    					saveUtils.saveStrSP(KeepingData.An_Jian_Ji_Fei_Url,
    							str.getString("url"));
    				}
    				bannerlist.add(bannerlistbean);
    			}
    		} catch (JSONException e) {
    			e.printStackTrace();
    		}
    	}
    
    	/** 回调用户选中城市结果方法 **/
    	@Override
    	public void onActivityResult(int requestCode, int resultCode, Intent data) {
    		super.onActivityResult(requestCode, resultCode, data);
    		if (saveUtils.getStrSP(KeepingData.User_City) != "") {
    			loction_text.setText(saveUtils.getStrSP(KeepingData.User_City));
    			get_banner_list();
    			get_func_button_list();
    		}
    	}
    
    	/** dp px 转换工具方法 **/
    	private int dp2px(int dp) {
    		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
    				getResources().getDisplayMetrics());
    	}
    }
    

      布局就省略了。

  • 相关阅读:
    acceptorThreadCount
    spring boot tomcat 线程数 修改初始线程数 统计性能 每百次请求耗时
    java 获取当前进程id 线程id
    Linux操作系统中打开文件数量的查看方法
    java.io.IOException: Too many open files
    随机采样 算法
    Spring Boot
    您好,python的请求es的http库是urllib3, 一个请求到贵司的es节点,想了解下,中间有哪些网关啊?冒昧推测,贵司的部分公共网关与python-urllib3的对接存在异常?
    运行状态:锁定中(实例空间满自动锁)
    。。。。。。不带http https : 不报错 spring boot elasticsearch rest
  • 原文地址:https://www.cnblogs.com/spring87/p/4422879.html
Copyright © 2020-2023  润新知