Hari krishna
Hari krishna

Reputation: 1152

Disable Viewpager swipe on Horizontal list touch

I have a ViewPager and inside that ViewPager I am loading all the contents by using adapter. Unfortunately i have Horizontal Listview in those contents, When I am trying to swipe Horizontal Listview entire ViewPager is swiping. Is there any solution for that? Thanks in anticipation.

This is My ViewPager Layout Code.

<com.devpoint.common.CustomViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"   
        android:id="@+id/pager"
        android:background="#e5e5e5" 
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

and this is my Single Item Inside ViewPager

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e5e5e5" >

    <ScrollView
        android:id="@+id/scrollviewid"
        android:layout_width="match_parent"
        android:layout_height="match_parent" 
        android:padding="5dp" >

        <TableLayout
            android:id="@+id/tableview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" > 


            <android.support.v7.widget.CardView
                android:id="@+id/cardview"
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/liteam_fronmargin"
                android:background="#e5e5e5"
                android:clickable="true"
                android:orientation="vertical"
                android:padding="35dp"
                android:tag="front"
                card_view:cardCornerRadius="@dimen/liteam_cradius" > 




                <TableRow
                    android:layout_width="match_parent"
                    android:layout_height="150dp"
                    android:background="#e5e5e5"
                    android:gravity="center_horizontal"
                    android:orientation="horizontal" >



                          <com.devpoint.adapter.HorizontalListView
                                android:id="@+id/gridview"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:columnWidth="60dp"
                                android:layout_gravity="center"
                                android:horizontalSpacing="10dp"
                                android:numColumns="3"
                                android:padding="10dp"
                                android:stretchMode="columnWidth"
                                android:verticalSpacing="10dp" />
                </TableRow>



              </android.support.v7.widget.CardView>   


              <!-- <android.support.v7.widget.CardView

                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/liteam_fronmargin"
                android:clickable="true"
                android:orientation="vertical"
                android:padding="35dp"
                android:tag="front"
                card_view:cardCornerRadius="@dimen/liteam_cradius" >

                <TableRow
                    android:id="@+id/retailer_mobileno_layout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center_horizontal"
                    android:orientation="horizontal"
                    android:padding="10dp" >

                    <fragment
                        android:id="@+id/map"
                        android:layout_width="@dimen/single_mapwidth"
                        android:layout_height="@dimen/single_mapheight"
                        android:layout_alignParentBottom="true"
                        android:layout_centerHorizontal="true"
                        class="com.google.android.gms.maps.SupportMapFragment" />
                </TableRow>
            </android.support.v7.widget.CardView> --> 

                  <TableRow

                    android:layout_width="match_parent"
                    android:layout_height="150dp"
                    android:background="#e5e5e5"
                    android:gravity="center_horizontal"
                    android:orientation="horizontal" >
                <ImageView 
                        android:id="@+id/btn_map"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:src="@drawable/map_location"
                        android:layout_weight="0.4"
                        android:layout_alignParentTop="true"
                        android:layout_marginTop="@dimen/userplace_btntop"/>

                </TableRow> 

        </TableLayout>
  </ScrollView>


</FrameLayout>

and my Adapter look like this

public ViewPagerAdapter(Context context, List<ListDetails> products,
            android.app.FragmentManager fragmentManager) {
        this.context = (Activity) context;
        this.products = products;

        // productNew =(CopyOnWriteArrayList<ListDetails>) products;

    }

    public void setPages(int x) {
        this.pages = x;
    }

    @Override
    public int getCount() {
        pages = products.size();
        return products.size();
    }

    public ListDetails getItem(int position) {
        return products.get(position);
    }

    private class ViewHolder {
        TextView txt_offer;
        TextView txt_distance;
        TextView txt_shop;
        TableLayout tbldetails;
        RatingBar rat_user;
        ImageView viewdetails;
        TextView txt_posteddate;
        TextView txt_enddate;
        TextView txt_category;
        TextView txt_couponcode;

        Button btnrating;

        HorizontalListView swipelisview;

        ScrollView scrollview;

        CardView card;

        ImageView map;

        CirclePageIndicator mIndicator;
        ViewPager viewPager;
        FloatingActionButton btn_call;
        FloatingActionButton btn_message;
        FloatingActionButton btn_del;
        FloatingActionButton btn_Mail;
        FloatingActionButton btn_review;
        FloatingActionButton btn_chat;

        FloatingActionsMenu fmenu;
        FloatingActionsMenu fmenu1;

    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        if (object != null) {
            return ((FrameLayout) object) == view;
        } else {
            return false;
        }
    }

    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @SuppressLint("InflateParams")
    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {

        LayoutInflater li = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (itemView == null) {
            if (alertLayout == null)

                alertLayout = li.inflate(R.layout.map_dialog, null);

        }

        try {

            // if(itemView == null)
            // {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            itemView = inflater.inflate(R.layout.single, container, false);
            // }

        } catch (InflateException e) {

            e.printStackTrace();

        }
        try {

            holder = new ViewHolder();
            holder.txt_offer = (TextView) itemView
                    .findViewById(R.id.Offer_edittext);
            holder.txt_distance = (TextView) itemView
                    .findViewById(R.id.distance_edittext);
            holder.txt_shop = (TextView) itemView
                    .findViewById(R.id.Shop_edittext);
            holder.tbldetails = (TableLayout) itemView
                    .findViewById(R.id.tablevielw);
            holder.rat_user = (RatingBar) itemView
                    .findViewById(R.id.user_ratingbar);
            holder.viewdetails = (ImageView) itemView
                    .findViewById(R.id.btn_details);
            holder.txt_posteddate = (TextView) itemView
                    .findViewById(R.id.offerPosted_edittext);
            holder.txt_enddate = (TextView) itemView
                    .findViewById(R.id.OfferEnd_edittext);
            holder.txt_category = (TextView) itemView
                    .findViewById(R.id.category_edittext);
            holder.txt_couponcode = (TextView) itemView
                    .findViewById(R.id.Coupon_edittext);

            holder.btnrating = (Button) itemView.findViewById(R.id.btn_rating);

            holder.swipelisview = (HorizontalListView) itemView
                    .findViewById(R.id.gridview);



            // holder.swipelisview.setOnTouchListener(mSuppressInterceptListener);



            holder.swipelisview.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    //DetailsViewpagerFragment.viewPager.setEnabled(false); 
                    DetailsViewpagerFragment.viewPager.setSwipeable(false);

                    DetailsViewpagerFragment.viewPager.setEnabled(false);

                    holder.scrollview.setEnabled(false);
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_UP:
                            //DetailsViewpagerFragment.viewPager.setEnabled(true);
                            DetailsViewpagerFragment.viewPager.setSwipeable(true);
                            holder.scrollview.setEnabled(true);
                            break;
                    }
                    return false;
                }
            });


            ((ViewPager) container).addView(itemView, 0);

            // return itemView;
        } catch (Exception e) {
            // PostLogcatErorrs(e);
        }

        return itemView;
    }


}

and My Main file Look Like this, Here I am Calling Viewpager adapter

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        try {

                try { 
                    rootView = inflater.inflate(R.layout.details_viewpager_fragment, container, false);

                    //ViewPager mIndicator = (ViewPager) rootView.findViewById(R.id.pager);


                    GetOfferShopList();
                } catch (InflateException e) {
                    PostLogcatErorrs(e);
                } 


        } catch (Exception e) {
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG)
                    .show();
            e.printStackTrace();
            PostLogcatErorrs(e);


        }
        return rootView;
    }


    private void GetOfferShopList() {
        try {

            final Location CurrentLocation = new Location(
                    getString(R.string.point_A));
            CurrentLocation.setLatitude(latitude);
            CurrentLocation.setLongitude(longitude);
            ListItemsData = new CopyOnWriteArrayList<ListDetails>();
            // Creating volley request obj

                    JsonObjectRequest movieReq = new JsonObjectRequest(LoadActivity.BaseUri + "GetAllOffer?type=",
                            null, new Response.Listener<JSONObject>() {




                                @Override
                                public void onResponse(JSONObject response) {
                                    //Log.d(TAG, response.toString());

                                    JSONArray GetMG_AppointmentRequestResult = null;
                                    try {
                                        GetMG_AppointmentRequestResult = response.getJSONArray(getString(R.string.Json_offerresult));
                                    } catch (JSONException e1) {
                                        Toast.makeText(getActivity(), 
                                                e1.getMessage(), Toast.LENGTH_LONG).show();
                                        e1.printStackTrace();
                                    }
                                    // Parsing json
                                    for (int i = 0; i < GetMG_AppointmentRequestResult.length(); i++) {
                                        try {



                                            JSONObject obj = GetMG_AppointmentRequestResult.getJSONObject(i);

                                            ListDetails ListModelObj = new ListDetails();

                                            Location RetailerLocation = new Location(getString(R.string.point_B));
                                            RetailerLocation.setLatitude(Double.parseDouble(obj
                                                    .getString(  getString(R.string.Rlocaion_Lat)))); 
                                            RetailerLocation.setLongitude(Double.parseDouble(obj
                                                    .getString(  getString(R.string.Rlocaion_Lng))));
                                            float distance = CurrentLocation.distanceTo(RetailerLocation)/1000;

                                            float val = (float)Math.round(distance * 10) / 10;


                                            ListModelObj.setDistance(val);

                                            ListModelObj.setPosition_id(Integer.parseInt(obj.getString(getString(R.string.Shop_RegID))));
                                            ListModelObj.setShopName(obj.getString(getString(R.string.Shop_Name)));
                                            ListModelObj.setDescription(obj.getString(getString(R.string.Offer_Name)));
                                            ListModelObj.setLat(Double.parseDouble(obj.getString( getString(R.string.Rlocaion_Lat))));
                                            ListModelObj.setLng(Double.parseDouble(obj.getString(  getString(R.string.Rlocaion_Lng))));                                         
                                            ListModelObj.setDeal(obj.getString(getString(R.string.retailer_deal))); 
                                            ListModelObj.setPromoCode(obj.getString(getString(R.string.promo_code)));
                                            ListModelObj.setAreaName(obj.getString(getString(R.string.Area_Name)));

                                            ListModelObj.setOfferStatus(obj.getString( getString(R.string.Offer_Status)));
                                            ListModelObj.setCategoryName(obj.getString( getString(R.string.Category_Type)));

                                            ListModelObj.setPostedDate(obj
                                                    .getString( getString(R.string.Offer_StartDate)));


                                            ListModelObj.setOfferEndTime(obj
                                                    .getString( getString(R.string.Offer_EndTime)));

                                            ListModelObj.setOfferEndDate(obj
                                                    .getString( getString(R.string.Offer_EndDate)));

                                            ListModelObj.setOfferID(obj
                                                    .getString(getString(R.string.Offer_id)));


                                            ListModelObj.setImageName1(obj.getString(getString(R.string.single_ImageName)));

                                            String abc = obj.getString(getString(R.string.single_ImageName));
                                            String[] xyz = abc.split(",");

                                            ListModelObj.setListImage(LoadActivity.BaseUriImg 
                                                                                            + xyz[0]);  


                                            JSONObject aaa = obj.getJSONObject("result1");
                                            //ListModelObj.setJSONData(aaa.getJSONArray("GetAllOfferResult"));                                  





                                            ListItemsData1 = new CopyOnWriteArrayList<ListDetails>();

                                        // Parsing json
                                            for (int i1 = 0; i1 < aaa.getJSONArray("GetAllOfferResult").length(); i1++) {
                                                try {



                                                    JSONObject obj1 = aaa.getJSONArray("GetAllOfferResult").getJSONObject(i1);

                                                    ListDetails ListModelObj1 = new ListDetails();

                                                    Location RetailerLocation1 = new Location(getString(R.string.point_B));
                                                    RetailerLocation.setLatitude(Double.parseDouble(obj1
                                                            .getString(  getString(R.string.Rlocaion_Lat)))); 
                                                    RetailerLocation.setLongitude(Double.parseDouble(obj1
                                                            .getString(  getString(R.string.Rlocaion_Lng))));
                                                    float distance1 = CurrentLocation.distanceTo(RetailerLocation)/1000;

                                                    float val1 = (float)Math.round(distance * 10) / 10;


                                                    ListModelObj1.setDistance(val);

                                                    ListModelObj1.setPosition_id(Integer.parseInt(obj1.getString(getString(R.string.Shop_RegID))));
                                                    ListModelObj1.setShopName(obj1.getString(getString(R.string.Shop_Name)));
                                                    ListModelObj1.setDescription(obj1.getString(getString(R.string.Offer_Name)));
                                                    ListModelObj1.setLat(Double.parseDouble(obj1.getString( getString(R.string.Rlocaion_Lat))));
                                                    ListModelObj1.setLng(Double.parseDouble(obj1.getString(  getString(R.string.Rlocaion_Lng))));                                           
                                                    ListModelObj1.setDeal(obj1.getString(getString(R.string.retailer_deal))); 
                                                    ListModelObj1.setPromoCode(obj1.getString(getString(R.string.promo_code)));
                                                    ListModelObj1.setAreaName(obj1.getString(getString(R.string.Area_Name)));

                                                    ListModelObj1.setOfferStatus(obj1.getString( getString(R.string.Offer_Status)));
                                                    ListModelObj1.setCategoryName(obj1.getString( getString(R.string.Category_Type)));

                                                    ListModelObj1.setPostedDate(obj1
                                                            .getString( getString(R.string.Offer_StartDate)));


                                                    ListModelObj1.setOfferEndTime(obj1
                                                            .getString( getString(R.string.Offer_EndTime)));

                                                    ListModelObj1.setOfferEndDate(obj1
                                                            .getString( getString(R.string.Offer_EndDate)));

                                                    ListModelObj1.setOfferID(obj1
                                                            .getString(getString(R.string.Offer_id)));


                                                    ListModelObj1.setImageName1(obj1.getString(getString(R.string.single_ImageName)));

                                                    String abc1 = obj1.getString(getString(R.string.single_ImageName));
                                                    String[] xyz1 = abc1.split(",");

                                                    ListModelObj1.setListImage(LoadActivity.BaseUriImg 
                                                                                                    + xyz1[0]); 




                                                    ListItemsData1.add(ListModelObj1);

                                                } catch (JSONException e) {
                                                    Toast.makeText(getActivity(), 
                                                            e.getMessage(), Toast.LENGTH_LONG).show();
                                                    e.printStackTrace();
                                                }
                                            }






                                            ListModelObj.setJSONData(ListItemsData1);

                                            ListModelObj.setViewPage_id(i);




                                            ListItemsData.add(ListModelObj);

                                        } catch (JSONException e) {
                                            Toast.makeText(getActivity(), 
                                                    e.getMessage(), Toast.LENGTH_LONG).show();
                                            e.printStackTrace();
                                            PostLogcatErorrs(e);
                                        }
                                    }

                                     viewPager = (CustomViewPager) rootView.findViewById(R.id.pager);
                                    viewPager.setCurrentItem(0);    

                                     adapter = new ViewPagerAdapter(getActivity(), ListItemsData , getActivity().getFragmentManager());
                                    // Binds the Adapter to the ViewPager

                                    viewPager.setAdapter(adapter);  
                                    //adapter.notifyDataSetChanged();
                                    viewPager.setCurrentItem(ClickListID);  
                                    viewPager.setOffscreenPageLimit(3);
                                    //adapter.notifyDataSetChanged();

                                    //viewPager.setOffscreenPageLimit(3);

                                }
                            }, new Response.ErrorListener() { 
                                @Override
                                public void onErrorResponse(VolleyError error) {





                                }
                            });

                    AppController.getInstance().addToRequestQueue(movieReq);
        } catch (Exception e) {
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG)
                    .show();
            e.printStackTrace();
            PostLogcatErorrs(e);
        }


    }
}

Upvotes: 2

Views: 2789

Answers (2)

Android Tutorial
Android Tutorial

Reputation: 829

This is the code for nonSwipeable viewpager... hopefully it will work for you

public class NonSwipeableViewPager extends ViewPager {

    public NonSwipeableViewPager(Context context) {
    super(context);
    } 

    public NonSwipeableViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
    } 

   @Override 
  public boolean onInterceptTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages 
    return false; 
  } 

  @Override 
  public boolean onTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages 
    return false; 
  } 
} 

Upvotes: 1

codezjx
codezjx

Reputation: 9142

Try following code: when there has move event in your Horizontal Listview, call requestDisallowInterceptTouchEvent(true) to forbid intercept touch events from ViewPager, when UP event coming, just set to false. See the Official Document

holder.swipelisview.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                view.getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                view.getParent().requestDisallowInterceptTouchEvent(false);
                break;
        }
        return false;
    }
});

Or maybe you can extends the ViewPager, and override the onInterceptTouchEvent(MotionEvent pEvent) method to decide whether to intercept all touch screen motion events. See the Official Document.

Upvotes: 2

Related Questions