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());
}
}
布局就省略了。
Android viewpager 嵌套 viewpager滑动 点击事件冲突解决方案的更多相关文章
- Android Listview中Button按钮点击事件冲突解决办法
今天做项目时,ListView中含有了Button组件,心里一早就知道肯定会有冲突,因为以前就遇到过,并解决过,可惜当时没有记录下来. 今天在做的时候,继续被这个问题郁闷了一把,后来解决后,赶紧来记录 ...
- ViewPager嵌套ViewPager后子ViewPager滑动不正常问题
ViewPager嵌套ViewPager后,滑动事件没法在子ViewPager里面响应. 解决办法是自定义子ViewPager. 以下代码是转载的,经本人测试,可以用!!! 转载地址:http://b ...
- Android监听消息通知栏点击事件
Android监听消息通知栏点击事件 使用BroadCastReceiver 1 新建一个NotificationClickReceiver 类,并且在清单文件中注册!! public class N ...
- 李氏滑动事件冲突解决方案 之 处理子ViewGroup的超棒方案
父ViewGroup(CurView) 和 子 ViewGroup(ParentView) 滑动事件冲突解决方案 之 处理子ViewGroup的超棒方案: 子ViewGroup 以 SlipRelat ...
- GridView的点击事件冲突解决
在开发的时候,常常可能遇到ListView或GridView控件点击事件与Item点击事件冲突的问题.原因是Item布局中的button或ImageButton强制获取了item的焦点,解决方案之中的 ...
- iOS UITapGestureRecognizer手势和UIButton 以及UITabelView点击事件冲突
一:在同一个view上加载,UITapGestureRecognizer手势,UIButton 行为,UITabelView点击事件冲突: 二:解决方式: 在UITapGesttureRecogniz ...
- Android ViewPager嵌套ViewPager滑动冲突处理方法
dispatchTouchEvent方法用于事件的分发,Android中所有的事件都必须经过这个方法的分发, 然后决定是自身消费当前事件还是继续往下分发给子控件处理.返回true表示不继续分发,事件没 ...
- Android ScrollView嵌套ViewPager,嵌套的ViewPager无法显示
记录:ScrollView嵌套ViewPager,嵌套的ViewPager无法显示 项目中所需要布局:LinearLayout中包含(orientation="vertical") ...
- ViewPager和Fragment中的View的点击事件冲突
ViewPager属于父布局,View属于子布局: 触摸事件是先到父View,再到子View,所以可以让ViewPager取消拦截事件: public class ComposeViewPager e ...
随机推荐
- UVa 10562 Undraw the Trees
题意: 将树的关系用字符串的形式给出 分析: 直接dfs搜索,第i行第j个如果是字母,判断i+1行j个是不是'|'是的话在第i+2行找第一个'-',找到后在第i+3行找字母,重复进行. 代码: #in ...
- Log4net 参数详解
<log4net> <!-- 错误日志类--> <logger name="logerror"> <level value="A ...
- WPF基础
1.Sender 指的是被点击的控件.默认为object类. private void btnc1_Click(object sender, RoutedEventArgs e) { Button b ...
- 使用 Struts2 校验器校验用户注册信息
基于验证框架的输入校验 一.创建一个struts2项目testValidators.Struts2 初体验:http://www.cnblogs.com/likailan/p/3280820.html ...
- php的SQL连接操作的方法
初学php,于是一开始就在sql(具体点说是mysql)里受挫严重.于是这里记下一些方法. 首先是基本方法.基本方法现在我不用了,所以我就附一下hustoj中的部分吧 基本方法的数据库连接操作: if ...
- 12行代码 让浏览器崩溃,iPhone重启
<html> <body> <script> var total=""; for (var i=0;i<1000000;i++) { ...
- SQLite header and source version mismatch 解决方案
我下载了sqlite源码,并且configure, make, make install. 然后就出现SQLite header and source version mismatch 的错误. 上 ...
- 图像 - 创建 头像V1.0
byte[] logo //处理群头像信息 //byte[] logoByte = Convert.FromBase64String(logo); ////1.0 System.IO.MemorySt ...
- Android 禁止软键盘自动弹出
Android系统对EditText这个控件有监听功能,如果某个Activity中含有该控件,就会自动弹出软键盘让你输入,这个看似人性化的方案有 时候并不被用户喜欢的,所以在有些情况下要禁用该功能.这 ...
- 弱类型语言中的0和空字符串(''或"")以及字符串'0'
在弱类型语言(js/PHP)中, 当我们用==判断0和'0'以及空字符串(''或"")是否相等的时候, 返回的是true. 而且在PHP中, 当我们用==判断0和null是否相等的 ...