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

简介: 为了解决这个问题。可以自定义viewpager,然后在里面监听首饰,自定义点击事件   package com.hpuvoice.view; import android.content.

为了解决这个问题。可以自定义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());
	}
}

  布局就省略了。

目录
相关文章
|
6天前
|
安全 搜索推荐 程序员
深入探索Android系统的碎片化问题及其解决方案
在移动操作系统的世界中,Android以其开放性和灵活性赢得了广泛的市场份额。然而,这种开放性也带来了一个众所周知的问题——系统碎片化。本文旨在探讨Android系统碎片化的现状、成因以及可能的解决方案,为开发者和用户提供一种全新的视角来理解这一现象。通过分析不同版本的Android系统分布、硬件多样性以及更新机制的影响,我们提出了一系列针对性的策略,旨在减少碎片化带来的影响,提升用户体验。
|
1月前
|
开发框架 移动开发 Android开发
安卓与iOS开发中的跨平台解决方案:Flutter入门
【9月更文挑战第30天】在移动应用开发的广阔舞台上,安卓和iOS两大操作系统各自占据半壁江山。开发者们常常面临着选择:是专注于单一平台深耕细作,还是寻找一种能够横跨两大系统的开发方案?Flutter,作为一种新兴的跨平台UI工具包,正以其现代、响应式的特点赢得开发者的青睐。本文将带你一探究竟,从Flutter的基础概念到实战应用,深入浅出地介绍这一技术的魅力所在。
72 7
|
2月前
|
开发框架 前端开发 Android开发
安卓与iOS开发中的跨平台解决方案
【9月更文挑战第27天】在移动应用开发的广阔天地中,安卓和iOS两大操作系统如同双子星座般耀眼。开发者们在这两大平台上追逐着创新的梦想,却也面临着选择的难题。如何在保持高效的同时,实现跨平台的开发?本文将带你探索跨平台开发的魅力所在,揭示其背后的技术原理,并通过实际案例展示其应用场景。无论你是安卓的忠实拥趸,还是iOS的狂热粉丝,这篇文章都将为你打开一扇通往跨平台开发新世界的大门。
|
28天前
|
Android开发
Android开发显示头部Bar的需求解决方案--Android应用实战
Android开发显示头部Bar的需求解决方案--Android应用实战
19 0
|
3月前
|
前端开发 开发工具 Android开发
探索安卓与iOS应用开发:跨平台解决方案的崛起
【8月更文挑战第27天】在移动设备日益普及的今天,安卓和iOS系统占据了市场的主导地位。开发者们面临着一个重要问题:是选择专注于单一平台,还是寻找一种能够同时覆盖两大系统的解决方案?本文将探讨跨平台开发工具的优势,分析它们如何改变了移动应用的开发格局,并分享一些实用的开发技巧。无论你是新手还是资深开发者,这篇文章都将为你提供有价值的见解和建议。
|
3月前
|
Android开发
Android编译出现Warning: Mapping new ns to old ns的解决方案
Android编译出现Warning: Mapping new ns to old ns的解决方案
305 3
|
3月前
|
前端开发 JavaScript Android开发
安卓与iOS开发中的跨平台解决方案
【8月更文挑战第24天】在移动应用开发领域,安卓和iOS两大平台占据了主导地位。然而,为这两个平台分别开发和维护应用会带来额外的时间和成本。本文将探讨跨平台开发的概念、优势以及流行的跨平台框架,如React Native和Flutter,并分析它们如何解决多平台开发的挑战。
|
Android开发 容器
Android小技巧之无限循环的ViewPager
前言 之所以会写着篇文章的原因是我现在项目用运用到了广告轮播(BannerView),当时在赶项目的时候在github上面找到了符合的开 源库 就直接引用了,但是该开源库稍微有点庞大,功能比较繁多。
1192 0