自定义ScrollView嵌套Pageview和GridView(ListView)的相关问题

原创 2015年11月17日 17:43:40

问题一:

           返回该界面,页面不在页首。

           解决办法:

                       

     gridView.setFocusable(false); //对Gridview设置(listview)
     scrollView.smoothScrollTo(0,20);  //显示页首


问题二:

             pageView水平滑动和scrollView垂直滑动的冲突,以及点击事件的冲突。

              解决办法:

                      1.在pageView里屏蔽组件监听,使在LinearLayout里面得监听无效,这样滑动的冲突解决了

                      2.在pageView写一个监听的接口留给LinearLayout实现,这里的监听自我感觉不是一个好的解决方法,在onTouch方法里写的监听。

                      3.由于是页面的activity(frament)实现监听,LinearLayout继续讲监听抛出。

                      4. 在使用LinearLayout的页面activity(frament)里实现监听的方法。

 

由于楼主也是初入android大门没多久,所以解决办法存在很多不足和局限性,希望各路大神提出更好的解决办法。



下面贴代码:

IndexFragment.java

package com.pactera.ishop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.pactera.ResideMenu.ResideMenu;
import com.pactera.bean.MerchantsInfo;
import com.pactera.bean.StoreInfo;
import com.pactera.common.Common;
import com.pactera.imagecycleview.ADInfo;
import com.pactera.imagecycleview.CycleViewPager;
import com.pactera.imagecycleview.ImageCycleView;
import com.pactera.imagecycleview.ImageCycleView.ImageCycleViewListener;
import com.pactera.imagecycleview.MyApplication;
import com.pactera.util.CustomScrollView;
import com.pactera.util.CustomScrollView.OnLoadListener;
import com.pactera.util.CustomScrollView.OnRefreshListener;
import com.pactera.util.DialogUtil;
import com.pactera.util.HttpUtils;
import com.pactera.util.HttpUtils.NetException;
import com.pactera.util.MyGridView;
import com.pactera.util.NetConnectivityManager;
import com.pactera.util.PositionUtil;

public class IndexFragment extends Fragment implements OnClickListener {
	 
    private int startIndex = 1;  
    
    private List<JSONObject> list_array = new ArrayList<JSONObject>(); 
    
	private MyApplication my_application;
	
	private View messageLayout;
	
	private ImageCycleView mAdView;
	
	private LinearLayout left_ll;
	
	private ImageView catgory;
	
	private MyGridView gridView;
	
	private Dialog loading;
	
	private int totalpage = 0;
	
	private static String store_name;
	
	private gAdapter adapter;

	private static TextView cityName;
	private ImageView menu;
	
	private CustomScrollView scrollView = null;

	private ArrayList<ADInfo> infos = new ArrayList<ADInfo>();

	private String[] imageUrls = { Common.URL_Logo1, Common.URL_Logo2,
			Common.URL_Logo3, Common.URL_Logo4, Common.URL_Logo5 };

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				CustomScrollView.flag = 1;
				break;
			case 2:
					adapter = new gAdapter(getActivity());
					gridView.setAdapter(adapter);
					gridView.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> arg0, View v,
								int arg2, long arg3) {
							JSONObject merchant;
							try {
								merchant = list_array.get(arg2);
								Intent i = new Intent();
								String url = merchant.get("imgpath").toString();
								i.putExtra("url", url);
								i.putExtra("mId", merchant.get("mer_id").toString());
								i.putExtra("price", merchant.get("price")
										.toString());
								i.setClass(getActivity(),
										MerchantDetailActivity.class);
								startActivity(i);
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
					});
					loading.hide();	
				break;
			case 3:
				loading.hide();
				break;

			default:
				break;
			}
		}

	};

	
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		messageLayout = inflater.inflate(R.layout.index_layout, container,
				false);
		scrollView = (CustomScrollView) messageLayout.findViewById(R.id.custom_scroll_view);
		my_application = (MyApplication) getActivity().getApplication();
		
		mAdView =(ImageCycleView) messageLayout.findViewById(R.id.ad_view);
		
		gridView =(MyGridView) messageLayout.findViewById(R.id.index_gview);
		gridView.setFocusable(false);
		for (int i = 0; i < imageUrls.length; i++) {
			ADInfo info = new ADInfo();
			info.setUrl(imageUrls[i]);
			info.setContent(String.valueOf(i));
			infos.add(info);
		}
		scrollView.smoothScrollTo(0,20);
		//下拉
		scrollView.setOnRefreshListener(new OnRefreshListener() {
			public void onRefresh() {
				new AsyncTask<Void, Void, Void>() {
					protected Void doInBackground(Void... params) {
						try {
							Thread.sleep(1500);
						} catch (Exception e) {
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						startIndex = 1;
						CustomScrollView.flag = 0;
						list_array.clear();
						setData(startIndex);
						scrollView.onRefreshComplete();
					}

				}.execute();
			}
		});

		//上拉
		scrollView.setOnLoadListener(new OnLoadListener() {
			public void onLoad() {
				new AsyncTask<Void, Void, Void>() {
					protected Void doInBackground(Void... params) {
						try {
							Thread.sleep(1500);
						} catch (Exception e) {
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						setData(++startIndex);
						scrollView.onLoadComplete();
					}

				}.execute();
			}
		});
		
		mAdView.setImageResources(infos, mAdCycleViewListener);
		catgory = (ImageView) messageLayout.findViewById(R.id.catgory);
		menu = (ImageView) messageLayout.findViewById(R.id.menu);	
		
		menu.setOnClickListener(this);
		loading = DialogUtil.createLoadingDialog(this.getActivity(), "数据加载中");
		loading.show();

		setData(startIndex);

		return messageLayout;
	}

	private void setData(final int int_currentPage) {
		StoreInfo s = (StoreInfo)my_application.getStore();
		if (s == null) {
			s = new StoreInfo();
		}
		//cityName.setText(PositionUtil.CITY + "\n" + s.getStoreName());
		new Thread() {
			@Override
			public void run() {
				Map<String, String> params = new HashMap<String, String>();
				if (NetConnectivityManager.getActiveNetwork(getActivity())) {

					String res = new String();
					params.put("currentPage",String.valueOf(int_currentPage));
					try {
						//http://221.122.78.102:8899/ishop/ePlatform/mobile/queryIndexMerchants.do?currentPage=2
						res = HttpUtils.sendPostMessage(params,
								Common.URL_indexReques);
						System.out.println("res" + res);

						JSONObject json = new JSONObject(res);
						
						int now_page = Integer.parseInt(json.getString("currentPage"));
						
						totalpage =  Integer.parseInt(json.getString("totalPage"));
						if(now_page <= totalpage){
							if(now_page == totalpage)
								CustomScrollView.flag = 1;
							if (json.get("result").equals("0")) {
								JSONArray list_rusult = new JSONArray();
								list_rusult = json.getJSONArray("data");
								Message msg = new Message();
								msg.what = 2;
						        for (int i = 0; i < list_rusult.length(); i++) {  
						            list_array.add(list_rusult.getJSONObject(i));  
						        }  
								mHandler.sendMessage(msg);
							}
							
						}
							
							
						

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						Log.e("jsonException", res);
						mHandler.sendEmptyMessage(1);
						e.printStackTrace();

						mHandler.sendEmptyMessage(1);
					} catch (NetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();

						System.out.println(e.errorCode);
						mHandler.sendEmptyMessage(1);
					}
				} else {

					mHandler.sendEmptyMessage(1);
				}

			}
		}.start();
	}

	   
	private ImageCycleViewListener mAdCycleViewListener = new ImageCycleViewListener() {

		@Override
		public void onImageClick(int ImageIndex,ADInfo info, int position, View view) {
			Toast.makeText(getActivity(), "imageindex---->" + ImageIndex, Toast.LENGTH_SHORT).show();
		}

		@Override
		public void displayImage(String imageURL, ImageView imageView) {
			ImageLoader.getInstance().displayImage(imageURL, imageView);
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.menu:

//			Intent intent = new Intent();
//			intent.setClass(getActivity(), StoreActivity.class);
//			startActivity(intent);
			MainActivity.resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
			break;
			
		case R.id.catgory:
//			Intent intent = new Intent();		
//			intent.setClass(getActivity(), MerchantSubActivity.class);
//			startActivity(intent);
			break;

		default:
			break;
		}
	}

	class gAdapter extends BaseAdapter {
		private LayoutInflater layoutInflater;
		private Context context;
		

		public gAdapter(Context context) {
			super();
			this.context = context;
			layoutInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return  list_array == null ? 0 :  list_array.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			try {
				return  list_array.get(position);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;  
			if (convertView == null) {
				holder = new ViewHolder(); 
				convertView = layoutInflater.inflate(R.layout.index_grid, null);
				holder.imageView = (ImageView) convertView
						.findViewById(R.id.grid_iv);
				holder.textView = (TextView) convertView
						.findViewById(R.id.grid_tv);
				holder.price = (TextView) convertView
						.findViewById(R.id.grid_price);
				holder.promotions = (TextView) convertView
						.findViewById(R.id.grid_promotions);
				holder.market_price = (TextView) convertView
						.findViewById(R.id.grid_market_price);
				convertView.setTag(holder); 
			}else{
				 holder = (ViewHolder) convertView.getTag(); 
			}
			JSONObject data;
			try {
				data =  list_array.get(position);
				MerchantsInfo merchant = new MerchantsInfo(data);
				String url = Common.img_ip + merchant.getImgpath();
				ImageLoader.getInstance().displayImage(url, holder.imageView);
				holder.textView.setText(merchant.getMer_name());
				holder.price.setText("¥" + merchant.getPrice() + "元");
				holder.promotions.setText(merchant.getPromotions());
				holder.market_price.setText("市场价: ¥" + merchant.getMarket_price());
				holder.market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return convertView;
		}
	}

    static class ViewHolder {  
		public ImageView imageView ;
		public TextView textView;
		public TextView price ;
		public TextView promotions;
		public TextView market_price;
    }
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		loading.dismiss();
		super.onDestroyView();
	}

}


Linearlayout.java


package com.pactera.imagecycleview;

import java.util.ArrayList;

import com.pactera.imagecycleview.CycleViewPager.OnCycleClickListener;
import com.pactera.ishop.R;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ImageCycleView extends LinearLayout {

	/**
	 * 上下文
	 */
	private Context mContext;
   public static boolean isMove=false;
	/**
	 * 图片轮播视图
	 */
	private CycleViewPager mBannerPager = null;

	/**
	 * 滚动图片视图适配器
	 */
	private ImageCycleAdapter mAdvAdapter;

	/**
	 * 图片轮播指示器控件
	 */
	private ViewGroup mGroup;

	/**
	 * 图片轮播指示器-个图
	 */
	private ImageView mImageView = null;

	/**
	 * 滚动图片指示器-视图列表
	 */
	private ImageView[] mImageViews = null;

	/**
	 * 图片滚动当前图片下标
	 */
	private int mImageIndex = 1;

	/**
	 * 手机密度
	 */
	private float mScale;


	
	public static int sImageIndex = 1;
	public ImageCycleView(Context context) {
		super(context);
	}


	public ImageCycleView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		mScale = context.getResources().getDisplayMetrics().density;
		LayoutInflater.from(context).inflate(R.layout.view_banner_content, this);
		mBannerPager = (CycleViewPager) findViewById(R.id.pager_banner);
		mBannerPager.setOnPageChangeListener(new GuidePageChangeListener());
		mBannerPager.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
					case MotionEvent.ACTION_UP:
						// 开始图片滚动
						startImageTimerTask();
						isMove=false;
						break;
					case MotionEvent.ACTION_DOWN:
						isMove=true;
						break;
					case MotionEvent.ACTION_MOVE:
						isMove=true;
						break;
					default:
						// 停止图片滚动
						stopImageTimerTask();
						break;
				}
				return false;
			}
		});
		// 滚动图片右下指示器视图
		mGroup = (ViewGroup) findViewById(R.id.viewGroup);
	}

	/**
	 * 装填图片数据
	 * 
	 */
	public void setImageResources(ArrayList<ADInfo> infoList, ImageCycleViewListener imageCycleViewListener) {
		// 清除所有子视图
		mGroup.removeAllViews();
		// 图片广告数量
		final int imageCount = infoList.size();
		mImageViews = new ImageView[imageCount];
		for (int i = 0; i < imageCount; i++) {
			mImageView = new ImageView(mContext);
			int imageParams = (int) (mScale * 20 + 0.5f);// XP与DP转换,适应不同分辨率
			int imagePadding = (int) (mScale * 5 + 0.5f);
			LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
			layout.setMargins(3, 0, 3, 0);
			mImageView.setLayoutParams(layout);
			//mImageView.setPadding(imagePadding, imagePadding, imagePadding, imagePadding);
			mImageViews[i] = mImageView;
			if (i == 0) {
				mImageViews[i].setBackgroundResource(R.drawable.icon_point_pre);
			} else {
				mImageViews[i].setBackgroundResource(R.drawable.icon_point);
			}
			mGroup.addView(mImageViews[i]);
		}
		mAdvAdapter = new ImageCycleAdapter(mContext, infoList, imageCycleViewListener,mBannerPager);
		mBannerPager.setAdapter(mAdvAdapter);
		startImageTimerTask();
	}

	/**
	 * 开始轮播(手动控制自动轮播与否,便于资源控制)
	 */
	public void startImageCycle() {
		startImageTimerTask();
	}

	/**
	 * 暂停轮播——用于节省资源
	 */
	public void pushImageCycle() {
		stopImageTimerTask();
	}

	/**
	 * 开始图片滚动任务
	 */
	private void startImageTimerTask() {
		stopImageTimerTask();
		// 图片每3秒滚动一次
		mHandler.postDelayed(mImageTimerTask, 3000);
	}

	/**
	 * 停止图片滚动任务
	 */
	private void stopImageTimerTask() {
		mHandler.removeCallbacks(mImageTimerTask);
	}

	private Handler mHandler = new Handler();

	/**
	 * 图片自动轮播Task
	 */
	private Runnable mImageTimerTask = new Runnable() {

		@Override
		public void run() {
			if (mImageViews != null) {
				// 下标等于图片列表长度说明已滚动到最后一张图片,重置下标
				if ((++mImageIndex) == mImageViews.length + 1) {
					mImageIndex = 1;
				}
				mBannerPager.setCurrentItem(mImageIndex);
				sImageIndex = mImageIndex;
			}
		}
	};

	/**
	 * 轮播监听器
	 * 
	 */
	private final class GuidePageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			if (state == ViewPager.SCROLL_STATE_IDLE)
				startImageTimerTask(); // 开始下次计时
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int index) {
			
			if (index == 0 || index == mImageViews.length + 1) {
				return;
			}
			// 图片滚动指示器背景
			mImageIndex = index;
			sImageIndex = index;
			index -= 1;
			mImageViews[index].setBackgroundResource(R.drawable.icon_point_pre);
			for (int i = 0; i < mImageViews.length; i++) {
				if (index != i) {
					mImageViews[i].setBackgroundResource(R.drawable.icon_point);
				}
			}

		}

	}

	private class ImageCycleAdapter extends PagerAdapter {

		/**
		 * 图片视图缓存列表
		 */
		private ArrayList<ImageView> mImageViewCacheList;

		/**
		 * 图片资源列表
		 */
		private ArrayList<ADInfo> mAdList = new ArrayList<ADInfo>();

		/**
		 * 图片点击监听器
		 */
		private ImageCycleViewListener mImageCycleViewListener;

		private CycleViewPager mBannerPager;
		private Context mContext;

		public ImageCycleAdapter(Context context, ArrayList<ADInfo> adList, ImageCycleViewListener imageCycleViewListener,CycleViewPager bannerPager) {
			mContext = context;
			mAdList = adList;
			mImageCycleViewListener = imageCycleViewListener;
			mImageViewCacheList = new ArrayList<ImageView>();
			this.mBannerPager = bannerPager;
		}
		
		@Override
		public int getCount() {
			return mAdList.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object obj) {
			return view == obj;
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
		    String imageUrl = mAdList.get(position).getUrl();
			ImageView imageView = null;
			if (mImageViewCacheList.isEmpty()) {
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			} else {
				imageView = mImageViewCacheList.remove(0);
			}
			// 设置图片点击监听
			imageView.setTag(imageUrl);
			mBannerPager.setCycleClickListener(new onClickofView(imageView,mImageCycleViewListener,mAdList,position));
			container.addView(imageView);
			mImageCycleViewListener.displayImage(imageUrl, imageView);
			return imageView;
		}


		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			ImageView view = (ImageView) object;
			container.removeView(view);
			mImageViewCacheList.add(view);
		}

	}

	/**
	 * 轮播监听事件
	 */
	public static interface ImageCycleViewListener {
          //加载
		public void displayImage(String imageURL, ImageView imageView);
		 // 单击
		public void onImageClick(int ImageIndex ,ADInfo info, int postion, View view);
	}

	public class onClickofView implements CycleViewPager.OnCycleClickListener{
		
		private ImageCycleViewListener mImageCycleViewListener;
		private ArrayList<ADInfo> mAdList;
		private int position;
        
        public onClickofView(ImageView imageView,ImageCycleViewListener mImageCycleViewListener,ArrayList<ADInfo> mAdList,int position) {
			// TODO Auto-generated constructor stub
        	this.mImageCycleViewListener = mImageCycleViewListener;
        	this.position = position;
        	this.mAdList = mAdList;
		}
		@Override
		public void onClick(View v, int ImageIndex) {			
			mImageCycleViewListener.onImageClick(ImageIndex,mAdList.get(position),position, v);
		}
		
	}


}



pageView.java


package com.pactera.imagecycleview;

import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.PointF;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

public class CycleViewPager extends ViewPager {
    PointF downP = new PointF();
    PointF curP = new PointF();
	long starttime = 0;
	long endtime = 0;
	
	private OnCycleClickListener clickListener;
	
	public interface OnCycleClickListener{
		
		public void onClick(View v, int ImageIndex);
	}
	
	public void setCycleClickListener(OnCycleClickListener clickListener){
		this.clickListener = clickListener;
	}
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent event) {
		return true;
	}

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		curP.x = ev.getX();
		curP.y = ev.getY();
		Date dt= new Date();

		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			downP.x = ev.getX();
			downP.y = ev.getY();
			starttime = dt.getTime();
			getParent().requestDisallowInterceptTouchEvent(true);
		}
		if (ev.getAction() == MotionEvent.ACTION_MOVE) {
			float distanceX = curP.x - downP.x;
			float distanceY = curP.y - downP.y;
			if (Math.abs(distanceX) > Math.abs(distanceY)) {
				getParent().requestDisallowInterceptTouchEvent(true);
			} else {
				getParent().requestDisallowInterceptTouchEvent(false);
			}
		}
		
		if(ev.getAction() == MotionEvent.ACTION_UP){
			float distanceX = curP.x - downP.x;
			float distanceY = curP.y - downP.y;
			endtime = dt.getTime();
			if((endtime-starttime) < 500 && Math.abs(distanceX) < 4 && Math.abs(distanceY) < 4 ){
				clickListener.onClick(this,ImageCycleView.sImageIndex);
			}
		}
		

		return super.onTouchEvent(ev);
	}


	
	private InnerPagerAdapter mAdapter;

	public CycleViewPager(Context context) {
		super(context);
		setOnPageChangeListener(null);
	}

	public CycleViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
		setOnPageChangeListener(null);
	}

	@Override
	public void setAdapter(PagerAdapter arg0) {
		mAdapter = new InnerPagerAdapter(arg0);
		super.setAdapter(mAdapter);
		setCurrentItem(1);
	}

	@Override
	public void setOnPageChangeListener(OnPageChangeListener listener) {
		super.setOnPageChangeListener(new InnerOnPageChangeListener(listener));
	}

	private class InnerOnPageChangeListener implements OnPageChangeListener {

		private OnPageChangeListener listener;
		private int position;

		public InnerOnPageChangeListener(OnPageChangeListener listener) {
			this.listener = listener;
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			if (null != listener) {
				listener.onPageScrollStateChanged(arg0);
			}
			if (arg0 == ViewPager.SCROLL_STATE_IDLE) {
				if (position == mAdapter.getCount() - 1) {
					setCurrentItem(1, false);
				} else if (position == 0) {
					setCurrentItem(mAdapter.getCount() - 2, false);
				}
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			if (null != listener) {
				listener.onPageScrolled(arg0, arg1, arg2);
			}
		}

		@Override
		public void onPageSelected(int arg0) {
			position = arg0;
			if (null != listener) {
				listener.onPageSelected(arg0);
			}
		}
	}

	private class InnerPagerAdapter extends PagerAdapter {

		private PagerAdapter adapter;

		public InnerPagerAdapter(PagerAdapter adapter) {
			this.adapter = adapter;
			adapter.registerDataSetObserver(new DataSetObserver() {

				@Override
				public void onChanged() {
					notifyDataSetChanged();
				}

				@Override
				public void onInvalidated() {
					notifyDataSetChanged();
				}

			});
		}

		@Override
		public int getCount() {
			return adapter.getCount() + 2;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return adapter.isViewFromObject(arg0, arg1);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			if (position == 0) {
				position = adapter.getCount() - 1;
			} else if (position == adapter.getCount() + 1) {
				position = 0;
			} else {
				position -= 1;
			}
			return adapter.instantiateItem(container, position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			adapter.destroyItem(container, position, object);
		}

	}
}




版权声明:本文为博主原创文章,未经博主允许不得转载。

解决ScrollView和GridListView和ListView滑动冲突方法(一)动态测量高度

效果 ListView测量的方法 /** * 因为listView和scollView会有冲突,所以需要动态给listView设置高度,这个方法就是动态测量listView的高度, ...

解决ScrollView下嵌套自定义ListView、GridView后依然显示不全的问题

当我们ScrollView下嵌套ListView、GridView时会出现显示不全的问题,这样我们大部分是会重写ListView、gridView 一:重写ListView、gridView 重...

自定义一个可以嵌套在ScrollView中使用的ListView和GridView

项目中可能要用到在ScrollView总嵌套使用listView 的时候,但是由于两个控件都是有上下滑动的事件,所以嵌套的时候使用Android自带的ListView是无法做到的,要自己定义一个Lis...

Android自定义控件(一) 下拉刷新,上拉分页加载更多(支持ListView, GridView, ScrollView)

项目中用到了下拉刷新和上啦加载

Android自定义控件(二) 下拉刷新,上拉分页加载更多(支持ListView, GridView, ScrollView)

接着上一篇,进行代码分析,先贴上 :

自定义LinearLayout,实现上拉下拉刷新,支持ListView,GridView,ScrollView

文章出处:http://gundumw100.iteye.com/blog/1764763 网上很多这样的效果都是继承某个具体的AdapterView或ScrollView,这样很不通用,如果继承自...
  • zhou699
  • zhou699
  • 2013年08月06日 10:06
  • 2556

关于scrollView中嵌套的ListView或者自定义view的焦点滑动问题

我在自定义一个可滚动的时间选择控件的时候遇到 当我滑动自动滚动控件的时候,响应的时scrollview,很纳闷,我明明在自定义view中重写了onTouchEvent方法 @Override pu...

计算并设置ListView的高度,防止嵌套ScrollView监听出现问题,(两种方法,一种自定义,一种测量)

listview嵌套
  • zyh0709
  • zyh0709
  • 2016年05月13日 10:15
  • 147

解决ScrollView下嵌套ListView、GridView显示不全的问题

1.使用网上用的动态改变listview高度的方法,该方法只适用于item布局是LinearLayout布局的情况,不能是其他的,因为其他的Layout(如RelativeLayout)没有重写onM...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:自定义ScrollView嵌套Pageview和GridView(ListView)的相关问题
举报原因:
原因补充:

(最多只允许输入30个字)