1. 程式人生 > >android viewpager 輪播圖點選事件失效

android viewpager 輪播圖點選事件失效

給ViewPager子控制元件新增點選事件無效。

需要新增ontouch監聽才可以,但是子控制元件新增ontouch事件返回false的話,只會響應down事件,所以要在viewpager新增ontouch事件,並且判斷移動距離,避免拖動viewpager失效

OnTouchListener mOnTouchListener=new OnTouchListener(){
            private int startX;
            private int startY;
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        startX = (int) event.getX();
                        startY = (int) event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        int endX = (int) event.getX();
                        int endY = (int) event.getY();
                        if (Math.abs(endX - startX) < 50 && Math.abs(endY - startY) < 50) {
                            try {
                                int itemIndex=top_viewpager.getCurrentItem();
                                HashMap map=top_viewpagerList.get(itemIndex);
                                String url=map.get("url").toString();
                                if(TextUtils.isEmpty(url)){
                                    try
                                    {
                                        HLog.showToast(getActivity(), R.string.url_invalid, Toast.LENGTH_SHORT);
                                    }
                                    catch (Exception e)
                                    {
                                        e.printStackTrace();
                                    }
                                    return false;
                                }
                                String title=map.get("title").toString();
                                Intent intent = new Intent();
                                intent.setClass(getActivity(), WebViewActivity.class);
                                intent.putExtra("url", url);
                                intent.putExtra("title", title);
                                startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                }
                return false;
            }
            
        };
        top_viewpager.setOnTouchListener(mOnTouchListener);