android - How to enable CardView in ViewPager -


i have tried using cardview in viewpager , everytime swipe left/right on cardview goes next screen. want card delete then. standalone both working fine when combine viewpager working , not cardswipe dismiss.

i tried disable viewpager code below code disables cardview swipe gestures. how can make cardview have gesture , when swipe in between 2 cards should have viewpager not connected card element.

or disable viewpager , use buttons , enable swipe on cardview. appreciate help. in advance.

fyi: have tried android_horizontal_listview in viewpager , works fine , this.

for viewpager:

mpager.setontouchlistener(new ontouchlistener() {                @override     public boolean ontouch(view v, motionevent event)     {         return true;     } }); 

for cardview:

swipeablerecyclerviewtouchlistener swipetouchlistener =  new swipeablerecyclerviewtouchlistener(mrecyclerview,     new swipeablerecyclerviewtouchlistener.swipelistener() {         @override         public boolean canswipe(int position) {             return true;         }          @override         public void ondismissedbyswipeleft(recyclerview recyclerview, int[] reversesortedpositions) {             (int position : reversesortedpositions) {                 mitems.remove(position);                 madapter.notifyitemremoved(position);             }             madapter.notifydatasetchanged();         }          @override         public void ondismissedbyswiperight(recyclerview recyclerview, int[] reversesortedpositions) {             (int position : reversesortedpositions) {                 mitems.remove(position);                 madapter.notifyitemremoved(position);             }             madapter.notifydatasetchanged();         }     });  mrecyclerview.addonitemtouchlistener(swipetouchlistener); 

mainactivity.java

public class mainactivity extends activity implements actionbar.tablistener {       viewpager vp;     view viewpager_layout_1;     view viewpager_layout_2;     view viewpager_layout_3;     actionbar.tab tab_1;     actionbar.tab tab_2;     actionbar.tab tab_3;     actionbar bar;     /////     string jsonstring1;     cardviewadapter spinnerarray;     imageloader imageloader = imageloader.getinstance();//     displayimageoptions options;     arraylist<hashmap<string, string>> array_list1;     recyclerview recyclerview;     relativelayout re1;     private context mcontext;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);          this.getwindow().setflags(windowmanager.layoutparams.flag_fullscreen, windowmanager.layoutparams.flag_fullscreen);         setcontentview(r.layout.activity_main);         mcontext = this;           viewpager_layout_1 = new view(mcontext);         viewpager_layout_1 = getlayoutinflater().inflate(r.layout.sample1, null);           viewpager_layout_3 = new view(mcontext);         viewpager_layout_3 = getlayoutinflater().inflate(r.layout.sample2, null);           viewpager_layout_2 = new view(mcontext);         viewpager_layout_2 = getlayoutinflater().inflate(r.layout.sample3, null);           vp = (viewpager) findviewbyid(r.id.vp);         bar = getactionbar();           bar.setnavigationmode(actionbar.navigation_mode_tabs);          bar.setdisplayshowtitleenabled(false);         bar.setdisplayshowhomeenabled(false);          vector<view> pages = new vector<view>();          pages.add(viewpager_layout_1);         pages.add(viewpager_layout_3);         pages.add(viewpager_layout_2);          custompageradapter adapter = new custompageradapter(mcontext, pages);         vp.setadapter(adapter);          vp.setonpagechangelistener(new viewpager.simpleonpagechangelistener() {              @override             public void onpageselected(int position) {                  bar.setselectednavigationitem(position);             }         });          tab_1 = bar.newtab();         tab_1.setcustomview(r.layout.tab_layout_1);         tab_1.settablistener(this);         bar.addtab(tab_1);           tab_2 = bar.newtab();         tab_2.setcustomview(r.layout.tab_layout_2);         tab_2.settablistener(this);         bar.addtab(tab_2);           tab_3 = bar.newtab();         tab_3.setcustomview(r.layout.tab_layout_3);         tab_3.settablistener(this);         bar.addtab(tab_3);           ////           imageloader.init(imageloaderconfiguration.createdefault(mainactivity.this));           jsonstring1 = "[{\"category\":\"1\",\"no\":\"1\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/c/c3/jordan_by_lipofsky_16577.jpg\"},{\"category\":\"2\",\"no\":\"2\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/thumb/9/96/basketball_world_cup_2014.jpg/800px-basketball_world_cup_2014.jpg\"},{\"category\":\"3\",\"no\":\"3\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/4/4e/basketball_goal.jpg\"},{\"category\":\"4\",\"no\":\"4\",\"image\":\"http://upload.wikimedia.org/wikipedia/commons/1/10/basketball_through_hoop.jpg\"}]";          //////////          array_list1 = new arraylist<hashmap<string, string>>();         jsonarray arr = null;         try {             arr = new jsonarray(jsonstring1);             (int = 0; < arr.length(); i++) {                 jsonobject e1 = arr.getjsonobject(i);                 string category = e1.getstring("category").trim();                 string no = e1.getstring("no").trim();                 string image = e1.getstring("image").trim();                  hashmap<string, string> map = new hashmap<string, string>();                 map.put("category", category);                 map.put("no", no);                 map.put("image", image);                 // adding hashlist arraylist                 array_list1.add(map);             }           } catch (jsonexception e) {             // todo auto-generated catch block             e.printstacktrace();         }         onitemtouchlistener itemtouchlistener = new onitemtouchlistener() {             @override             public void oncardviewtap(view view, int position) {                 toast.maketext(mainactivity.this, "tapped " + array_list1.get(position), toast.length_short).show();             }              @override             public void onbutton1click(view view, int position) {                 toast.maketext(mainactivity.this, "clicked button1 in " + array_list1.get(position), toast.length_short).show();             }              @override             public void onbutton2click(view view, int position) {                 toast.maketext(mainactivity.this, "clicked button2 in " + array_list1.get(position), toast.length_short).show();             }         };          spinnerarray = new cardviewadapter(itemtouchlistener, mainactivity.this, array_list1);         recyclerview = (recyclerview) viewpager_layout_3.findviewbyid(r.id.recycler_view);         recyclerview.setlayoutmanager(new linearlayoutmanager(this));         slideinbottomanimationadapter alphaadapter = new slideinbottomanimationadapter(spinnerarray);         scaleinanimationadapter alphaadapter2 = new scaleinanimationadapter(alphaadapter);         final alphainanimationadapter alphaadapter3 = new alphainanimationadapter(alphaadapter2);         alphaadapter3.setduration(500);         alphaadapter3.setfirstonly(true);         recyclerview.setadapter(alphaadapter3);           final swipeablerecyclerviewtouchlistener swipetouchlistener =                 new swipeablerecyclerviewtouchlistener(recyclerview,                         new swipeablerecyclerviewtouchlistener.swipelistener() {                             @override                             public boolean canswipe(int position) {                                 return true;                             }                               @override                             public void ondismissedbyswipeleft(recyclerview recyclerview, int[] reversesortedpositions) {                                 (int position : reversesortedpositions) { //                                    mitems.remove(position);                                     toast.maketext(mainactivity.this, array_list1.get(position) + " swiped left", toast.length_short).show();                                     array_list1.remove(position);                                     alphaadapter3.notifyitemremoved(position);                                 }                                 alphaadapter3.notifydatasetchanged();                             }                              @override                             public void ondismissedbyswiperight(recyclerview recyclerview, int[] reversesortedpositions) {                                 (int position : reversesortedpositions) { //                                     toast.maketext(mainactivity.this, array_list1.get(position) + " swiped right", toast.length_short).show();                                     array_list1.remove(position);                                     alphaadapter3.notifyitemremoved(position);                                 }                                 alphaadapter3.notifydatasetchanged();                             }                         });          recyclerview.addonitemtouchlistener(swipetouchlistener);       }      @override     public void ontabreselected(actionbar.tab tab, fragmenttransaction ft) {         //  toast.maketext(getbasecontext(), tab.tostring(), 5).show();     }      @override     public void ontabselected(actionbar.tab tab, fragmenttransaction ft) {         //      toast.maketext(getbasecontext(), tab.tostring(), 5).show();         vp.setcurrentitem(tab.getposition());         if (tab.getposition() == 2) {               tab_2.setcustomview(null);             tab_2.setcustomview(r.layout.tab_layout_2);              tab_1.setcustomview(null);             tab_1.setcustomview(r.layout.tab_layout_1);               tab_3.setcustomview(null);             tab_3.setcustomview(r.layout.tab_layout_33);           } else if (tab.getposition() == 1) {               tab_2.setcustomview(null);             tab_2.setcustomview(r.layout.tab_layout_22);              tab_1.setcustomview(null);             tab_1.setcustomview(r.layout.tab_layout_1);               tab_3.setcustomview(null);             tab_3.setcustomview(r.layout.tab_layout_3);           } else if (tab.getposition() == 0) {              tab_1.setcustomview(null);             tab_1.setcustomview(r.layout.tab_layout_11);               if (tab_2 != null) {                  tab_2.setcustomview(null);                 tab_2.setcustomview(r.layout.tab_layout_2);             }               if (tab_3 != null) {                  tab_3.setcustomview(null);                 tab_3.setcustomview(r.layout.tab_layout_3);             }           }     }      @override     public void ontabunselected(actionbar.tab tab, fragmenttransaction ft) {         //  toast.maketext(getbasecontext(), tab.tostring(), 5).show();      }       public interface onitemtouchlistener {          // disallow touch request parent scroll on touch of child view           /**          * callback invoked when user taps 1 of recyclerview items          *          * @param view     cardview touched          * @param position index of item touched in recyclerview          */         public void oncardviewtap(view view, int position);          /**          * callback invoked when button1 of item touched          *          * @param view     button touched          * @param position index of item touched in recyclerview          */         public void onbutton1click(view view, int position);          /**          * callback invoked when button2 of item touched          *          * @param view     button touched          * @param position index of item touched in recyclerview          */         public void onbutton2click(view view, int position);     }      public class custompageradapter extends pageradapter {          private final context mcontext;         private final vector<view> pages;          public custompageradapter(context context, vector<view> pages) {             this.mcontext = context;             this.pages = pages;         }          @override         public object instantiateitem(viewgroup container, int position) {              view page = pages.get(position);             container.addview(page);               return page;         }          @override         public int getcount() {             return pages.size();         }          @override         public boolean isviewfromobject(view view, object object) {             return view.equals(object);         }          @override         public void destroyitem(viewgroup container, int position, object object) {             container.removeview((view) object);         }       }      public class cardviewadapter extends recyclerview.adapter<cardviewadapter.viewholder> {         arraylist<hashmap<string, string>> d;         activity a;         private list<string> cards;         private onitemtouchlistener onitemtouchlistener2;           public cardviewadapter(onitemtouchlistener onitemtouchlistener, activity a, arraylist<hashmap<string, string>> d) {             //  this.cards = cards;             this.onitemtouchlistener2 = onitemtouchlistener;             this.a = a;             this.d = d;         }          @override         public viewholder oncreateviewholder(viewgroup viewgroup, int i) {             view v = layoutinflater.from(viewgroup.getcontext()).inflate(r.layout.card_view_layout, viewgroup, false);             return new viewholder(v);         }          @override         public void onbindviewholder(viewholder viewholder, int i) {             //  viewholder.title.settext(cards.get(i));              hashmap<string, string> item = d.get(i);             viewholder.title.settext(item.get("category"));             imageloader.displayimage(item.get("image"), viewholder.im2);          }          @override         public int getitemcount() {             //   return d == null ? 0 : d.size();             return (null != d ? d.size() : 0);             // return d.size();         }          public class viewholder extends recyclerview.viewholder {              motionevent motionevent;             private int mslop;             private int mminflingvelocity;             private int mmaxflingvelocity;             private long manimationtime;             // fixed properties             //   private recyclerview mrecyclerview;             private swipeablerecyclerviewtouchlistener.swipelistener mswipelistener;              // transient properties             private int mviewwidth = 1; // 1 , not 0 prevent dividing 0             private int mdismissanimationrefcount = 0;             private float malpha;             private float mdownx;             private float mdowny;             private boolean mswiping;             private int mswipingslop;             private velocitytracker mvelocitytracker;             private int mdownposition;             private int manimatingposition = listview.invalid_position;             private view mdownview;             private boolean mpaused;             private float mfinaldelta;             ///             private textview title;             private button button1;             private button button2;             private imageview im2;              public viewholder(view itemview) {                 super(itemview);                 title = (textview) itemview.findviewbyid(r.id.card_view_title);                  im2 = (imageview) itemview.findviewbyid(r.id.imageview);              }         }     }   } 

activity_main.xml

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:id="@+id/relativelayout_1">       <linearlayout         android:layout_width="fill_parent"         android:layout_height="fill_parent"         android:layout_alignparentbottom="true"         android:layout_alignparentstart="true"         android:id="@+id/linearlayout_1"         android:orientation="vertical">          <android.support.v4.view.viewpager             android:id="@+id/vp"             android:layout_width="match_parent"             android:layout_height="0dp"              android:layout_weight="1"             />       </linearlayout>   </relativelayout> 

sample2.xml

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/re1"     android:layout_width="match_parent"     android:layout_height="match_parent"> <android.support.v7.widget.recyclerview     android:id="@+id/recycler_view"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:scrollbars="vertical">  </android.support.v7.widget.recyclerview>  </relativelayout> 

to solve issue used itemtouchhelper provided android swipe delete item recyclerview.

please see implementation below:

mainactivity:

here have implementation of viewpager , it's child fragments.

package za.co.gadgetgirl.testcardpager;  import android.os.bundle; import android.support.v4.app.fragment; import android.support.v4.app.fragmentmanager; import android.support.v4.app.fragmentpageradapter; import android.support.v4.view.viewpager; import android.support.v7.app.appcompatactivity;  import java.util.arraylist; import java.util.list;  public class mainactivity extends appcompatactivity {      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);          viewpager viewpager = (viewpager) findviewbyid(r.id.viewpager);         setupviewpager(viewpager);     }      private void setupviewpager(viewpager viewpager) {         adapter adapter = new adapter(getsupportfragmentmanager());          frag1 frag1 = new frag1();         frag2 frag2 = new frag2();         frag3 frag3 = new frag3();          adapter.addfragment(frag1, "frag1");         adapter.addfragment(frag2, "frag2");         adapter.addfragment(frag3, "frag3");         viewpager.setadapter(adapter);     }      static class adapter extends fragmentpageradapter {         private final list<fragment> mfragments = new arraylist<>();         private final list<string> mfragmenttitles = new arraylist<>();          public adapter(fragmentmanager fm) {             super(fm);         }          public void addfragment(fragment fragment, string title) {             mfragments.add(fragment);             mfragmenttitles.add(title);         }          @override         public fragment getitem(int position) {             return mfragments.get(position);         }          @override         public int getcount() {             return mfragments.size();         }          @override         public charsequence getpagetitle(int position) {             return mfragmenttitles.get(position);         }     } } 

frag1:

on fragment have recyclerview has itemtouchhelper attached. itemtouchhelper listens onswiped(...) method defined in simplecallback interface , remove swiped item in method.

package za.co.gadgetgirl.testcardpager;  import android.os.bundle; import android.support.annotation.nullable; import android.support.v4.app.fragment; import android.support.v7.widget.linearlayoutmanager; import android.support.v7.widget.recyclerview; import android.support.v7.widget.helper.itemtouchhelper; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup;  public class frag1 extends fragment {      @nullable     @override     public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) {         view v = inflater.inflate(r.layout.frag1, container, false);          final recyclerview rv = (recyclerview) v.findviewbyid(r.id.rv);         final linearlayoutmanager llm = new linearlayoutmanager(getactivity());         rv.setlayoutmanager(llm);          final rvadapter rvadapter = new rvadapter(person.initializedata());         rv.setadapter(rvadapter);          itemtouchhelper itemtouchhelper = new itemtouchhelper(new itemtouchhelper.simplecallback(0,itemtouchhelper.left|itemtouchhelper.right) {             @override             public boolean onmove(recyclerview recyclerview, recyclerview.viewholder viewholder, recyclerview.viewholder target) {                 return false;             }              @override             public void onswiped(recyclerview.viewholder viewholder, int direction) {                 rvadapter.removeitem(viewholder.getadapterposition());             }         });          itemtouchhelper.attachtorecyclerview(rv);          return v;     }  } 

rvadapter:

public class rvadapter extends recyclerview.adapter<rvadapter.personviewholder> {       //...implementation...      public void removeitem(int position) {         persons.remove(position);         notifyitemremoved(position);     } } 

to use itemtouchhelper, need appcompat-v7:22.2.0 dependency , above defined in app gradle file.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -