Block page swipe in a view pager programmatically - android

I am developing an app where the user can type in stuff in edittexts and get to the next view by swiping the screen. The swiping-stuff is handled by a viewpager.
What I want to do is the following:
The user should only be able to swipe when all edittexts are filled. Currently all my edittexts have a TextWatcher whichs sets a boolean value to "true" once every field is filled. When it is true, I want to enable the viewpager, when it isn't, I want to disable it.
I'm using a CustomViewPager with three Fragments. I post my CustomViewPager code:
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Toast;
public class CustomViewPager extends ViewPager {
private boolean isPagingEnabled;
public Context context;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.isPagingEnabled = true;
this.context = context;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (isPagingEnabled) {
return super.onTouchEvent(event);
}
Toast.makeText(context, "Please fill in the details, then swipe !",
Toast.LENGTH_LONG).show();
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (isPagingEnabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean b) {
isPagingEnabled = b;
}
}
PageViewActivity.java
public class PageViewActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
int pageId=0;
public static CustomViewPager pager;
PageListener pageListener;
int currentPage=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
pager =(CustomViewPager)findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
pager.setPagingEnabled(false);
pageListener = new PageListener();
pager.setOnPageChangeListener(pageListener);
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MyFragmentA.newInstance("Fragment 1"));
fList.add(MyFragmentB.newInstance("Fragment 2"));
fList.add(MyFragmentC.newInstance("Fragment 3"));
return fList;
}
public void next(View v){
if(pageId<=2)
{
pager.setCurrentItem(pageId);
}
pageId++;
}
private class PageListener extends SimpleOnPageChangeListener{
public void onPageSelected(int position) {
Log.i("test", "onPageSelected " + position);
currentPage = position;
}
//Called when the scroll state changes.
public void onPageScrollStateChanged(int state)
{
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
Log.i("test", "onPageScrolled " + position);
currentPage = position;
}
}
}
My Page Adapter is this:
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.widget.Toast;
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Finally I post one of my Fragments with the only relevant code:
public class MyFragmentA extends Fragment {
EditText editname;
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final MyFragmentA newInstance(String message)
{
MyFragmentA f = new MyFragmentA();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
editname = (EditText)myFragmentView.findViewById(R.id.name_input);
editname.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(editname.getText().toString().trim().length() == 0) {
// Can I set here isPagingEnabled = false??
Toast.makeText(getActivity(), "SwipeFlag false!", Toast.LENGTH_SHORT).show();
} else if(editname.getText().toString().trim().length() > 0) {
// Can I set here isPagingEnabled = true??
Toast.makeText(getActivity(), "SwipeFlag true!", Toast.LENGTH_SHORT).show();
}
}
});
return myFragmentView;
}
}
I know that the keypoint to block page swipe is to set the flag "isPagingEnabled" to false, but I can't understand what is the best way to set it from a Fragment at runtime.

Ok, I finally found a solution and I post it here.. The best way to block page swipe is to control if edit text is filled inside onPageScrolled in PageViewActivity.java (my MainActivity..):
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.i("test", "onPageScrolled - position = " + position);
currentPage = position;
txt1 = (EditText) findViewById(R.id.name_input);
if(position == 0) {
if(txt1.getText().toString().trim().length() == 0) {
pager.setCurrentItem(0);
} else if(txt1.getText().toString().trim().length() > 0) {
// DO NOTHING
}
}
}
In that way page swipe is not allowed until the edittext field of your fragment is filled.
Another wise way to block page swipe, but ONLY in the right direction is to modify onPageSelected in this way:
boolean inibitFlag = false;
int maxAllowedPage = 1; // .. or you can set this value in your fragment..
public void onPageSelected(int position) {
Log.i("test", "onPageSelected " + position);
if(inibitFlag)
return;
if(position > maxAllowedPage) {
inibitFlag = true;
pager.setCurrentItem(currentPage);
inibitFlag = false;
} else {
currentPage = position;
}
}
Hope this helps someone!!

Related

how to fix" 3 fragment in One activity with viewPager need validation first two page then possible to go third page"

I want to create a createOrderActivity where has three fragments like Service info, ScheduleInfo, confirmation
the service info fragment has editText
if click NextButton(which is situated CreateOrderActivity) check validation editText first. then move ScheduleFragment page.
if first two pages validation ok then move to Confirmation Fragment page.
Here is the FragmentViewpagerAdapter class
public class FragmentViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public FragmentViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
In CreateOrderActivity class
#Override
public void onPageSelected(int position) {
boolean checkSch= false;
if (position == 1) {
ServiceInfoFragment serviceInfoFragment = new ServiceInfoFragment();
//checking validation from ServiceInfoFragment fragment Class
if (serviceInfoFragment.checkServiceValidation()) {
checkSch = true;
//Toast.makeText(CreateOrderActivity.this, "Validation okay", Toast.LENGTH_SHORT).show();
}else {
checkSch = false;
// Toast.makeText(CreateOrderActivity.this, "Please check validation", Toast.LENGTH_SHORT).show();
pagerCreateOrder.setCurrentItem(position-1);
}
}
if (position == 2) {
if (checkSch){
ScheduleFragment scheduleFragment = new ScheduleFragment();
if (scheduleFragment.checkScheduleValidation()) {
Toast.makeText(CreateOrderActivity.this, "Validation okay", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(CreateOrderActivity.this, "Please check S validation", Toast.LENGTH_SHORT).show();
pagerCreateOrder.setCurrentItem(position-1);
}
}else {
Toast.makeText(CreateOrderActivity.this, "Please check validation", Toast.LENGTH_SHORT).show();
pagerCreateOrder.setCurrentItem(position-2);
}
}
}
//checking checkScheduleValidation() in ScheduleFragment class. return null exception
*bellow mehtod declear in Fragment *
public boolean checkServiceValidation(){
return true;
}
I upload this Image
I used this Reference
I found a solution in my way. I have loaded three fragments in a viewpager. In the second fragment, there is one edittext. on clicking the next button, there is a validation for checking email. On the basis of validation next fragment is loaded. All the Fragments are loaded as singleton . You might have caused null pointer exception , because of multiple instance of fragments.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private FragmentTwo fragmentTwo;
private ViewPager mViewPager;
Button back, next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
back = findViewById(R.id.back);
next = findViewById(R.id.next);
next.setOnClickListener(this);
back.setOnClickListener(this);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.vp_viewpager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
if (i==2){
if (!fragmentTwo.checkEditText()) {
Toast.makeText(getApplicationContext(),"False",Toast.LENGTH_LONG).show();
mViewPager.setCurrentItem(i-1);
return;
}
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private void changeViewPagerPosition(int position) {
int totalCount = mViewPager.getAdapter().getCount();
if (position < 0 || position >= totalCount) {
return;
}
mViewPager.setCurrentItem(position);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onClick(View view) {
int currentViewpagerPosition = mViewPager.getCurrentItem();
switch (view.getId()) {
case R.id.back:
changeViewPagerPosition(currentViewpagerPosition - 1);
break;
case R.id.next:
if (currentViewpagerPosition==1){
if (!fragmentTwo.checkEditText()) {
Toast.makeText(getApplicationContext(),"Falsee",Toast.LENGTH_LONG).show();
return;
}
}
changeViewPagerPosition(currentViewpagerPosition + 1);
break;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentOne.newInstance(position);
case 1:
return fragmentTwo=FragmentTwo.getInstance();
case 2:
return FragmentThree.newInstance(position);
default:
return FragmentThree.newInstance(position);
}
}
#Override
public int getCount() {
return 3;
}
}
}
The Fragment 2
public class FragmentTwo extends Fragment {
EditText email;
private static FragmentTwo fragment=null;
public FragmentTwo() {
}
public static FragmentTwo getInstance() {
if (fragment == null){
fragment = new FragmentTwo();
}
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
email = getView().findViewById(R.id.editText);
}
public boolean emailValidator()
{
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-" +
"9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email.getText().toString());
return matcher.matches();
}
public Boolean checkEditText(){
if (emailValidator()){
return true;
}
return false;
}
}

How to add tinder card animation in view pager

I am currently struggling with giving tinder card animation effect in my view pager.
I am new to animation and dont know much about it.
I am currently using :AndTinder library.
here is my view pager code.
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class ItemPagerFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private CursorPagerAdapter adapter;
private ImageButton favButton;
private ImageButton shareButton;
public ItemPagerFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.gc();
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_item_pager, container, false);
// Instantiate a ViewPager and a PagerAdapter in app.
mPager = (ViewPager) rootView.findViewById(R.id.pager);
getLoaderManager().initLoader(-5, null, this);
mPager.setOffscreenPageLimit(0);
adapter = new CursorPagerAdapter(getFragmentManager(), null);
mPager.setAdapter(adapter);
mPager.setOnPageChangeListener(new OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
public void onPageSelected(int position) {
//Toast.makeText(getActivity(),
//"Selected page position: " + ++position, Toast.LENGTH_SHORT).show();
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
return rootView;
}
#Override
public void onDestroyView() {
System.gc();
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader loader = new CursorLoader(getActivity(),
DataProvider.CONTENT_URI_DATA,
null,
null, // "favorite = 0"
null,
"RANDOM()");
return loader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
/**
* A simple pager adapter.
*/
private class CursorPagerAdapter extends FragmentStatePagerAdapter {
//HashMap<Integer,ItemDetailFragment> hash = new HashMap<Integer,ItemDetailFragment>();
ItemDetailFragment[] record = new ItemDetailFragment[3];
//HashMap<Integer,ItemDetailFragment> hash = new HashMap<Integer,ItemDetailFragment>(3);
private Cursor mCursor;
public CursorPagerAdapter(FragmentManager fm, Cursor c) {
super(fm);
mCursor = c;
}
#Override
public Fragment getItem(int position) {
if (mCursor.moveToPosition(position)) {
Bundle arguments = new Bundle();
arguments.putLong(ItemDetailFragment.ARG_ITEM_ID, mCursor.getLong(mCursor.getColumnIndex(DataProvider.COL_ID)));
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
// System.out.println("putting page " + position + " in " + position % 3);
record[position%3] = fragment;
//hash.put(position , fragment);
return fragment;
}
return null;
}
#Override
public int getCount() {
if (mCursor != null) {
return mCursor.getCount();
}
return 0;
}
public void swapCursor(Cursor cursor) {
mCursor = cursor;
try {
notifyDataSetChanged();
}
catch(Exception e)
{
System.out.println("exception caught");
}
}
public void destroyItem(ViewGroup container, int position, Object object){
record[position%3] = null;
super.destroyItem(container,position,object);
}
private ItemDetailFragment getfragment(int position)
{
return record[position%3];
//return hash.get(position);
}
public int getItemPosition(Object object) {
ItemDetailFragment f = (ItemDetailFragment ) object;
int position = mPager.getCurrentItem();
ItemDetailFragment current = adapter.getfragment(position);
if(current.equals(f))
{
int fav = Integer.parseInt(f.data.getFavorite());
if(fav == 1)
f.update(1);
else
f.update(0);
}
return super.getItemPosition(object);
}
//changes to be done here
/*public int getItemPosition(Object object) {
ItemDetailFragment f = (ItemDetailFragment ) object;
int position = mPager.getCurrentItem();
System.out.println("prerna update "+position);
ItemDetailFragment current = adapter.getfragment(position);
if(current.equals(f))
{
System.out.println("prerna got it");
int fav = Integer.parseInt(f.data.getFavorite());
if(fav == 1)
f.update(1);
else
f.update(0);
}
return super.getItemPosition(object);
// return POSITION_NONE;//comment afterwards
}*/
}
}
can anybody please help me to do this.

How to enable CardView in ViewPager

I have tried using CardView in ViewPager and everytime I swipe left/right on CardView it goes to the next screen. I want the card to delete itself then. Currently as a standalone both are working fine but when I combine then only viewpager is working and not cardswipe dismiss.
I tried to disable ViewPager with the code below but this code also disables CardView swipe gestures. How can I make only CardView to have gesture and when you swipe in between 2 cards then its should have ViewPager as its not connected to card element.
Or disable ViewPager completely and use it as buttons and enable swipe on CardView. I really appreciate any help. Thanks in Advance.
FYI: I have tried android_horizontal_listview in ViewPager and that works fine and exactly like 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) {
for (int position : reverseSortedPositions) {
mItems.remove(position);
mAdapter.notifyItemRemoved(position);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (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);
for (int i = 0; i < 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 to 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) {
for (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) {
for (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 {
// this will disallow the touch request for parent scroll on touch of child view
/**
* Callback invoked when the user Taps one of the RecyclerView items
*
* #param view the CardView touched
* #param position the index of the item touched in the RecyclerView
*/
public void onCardViewTap(View view, int position);
/**
* Callback invoked when the Button1 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the RecyclerView
*/
public void onButton1Click(View view, int position);
/**
* Callback invoked when the Button2 of an item is touched
*
* #param view the Button touched
* #param position the index of the item touched in the 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 and not 0 to prevent dividing by zero
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 this issue I used an ItemTouchHelper provided by Android to easily swipe to delete an item from a RecyclerView.
Please see implementation below:
MainActivity:
Here I have the implementation of the ViewPager and 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 this Fragment I have a RecyclerView that has an ItemTouchHelper attached. The ItemTouchHelper listens for the onSwiped(...) method that is defined in the SimpleCallback interface and I just remove the swiped item in this 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 the ItemTouchHelper, you will need the appcompat-v7:22.2.0 dependency and above defined in your app gradle file.
I haven't use SwipeableRecyclerView before so I cannot really say much. I have a problem same as you before. I solve it by handling onTouch event of the base container of fragment (such as LinearLayout,RelativeLayout) and it work for me. Why don't you try this solution and get back to us
For the use case that you are describing, I don't think that ViewPager is the class that you want to use to get your swipe action. It seems to me that the combination of CoordinatorLayout and SwipeDismissBehavior is more appropriate.
EDIT:
See my solution below:
Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.CardView>
</android.support.design.widget.CoordinatorLayout>
Activity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CardView cardView = (CardView) findViewById(R.id.cardView);
SwipeDismissBehavior<CardView> behavior = new SwipeDismissBehavior();
behavior.setSwipeDirection(SwipeDismissBehavior.SWIPE_DIRECTION_START_TO_END);
behavior.setListener(new SwipeDismissBehavior.OnDismissListener() {
#Override
public void onDismiss(View view) {
finish(); // close activity if desired
}
#Override
public void onDragStateChanged(int state) {
}
});
((CoordinatorLayout.LayoutParams) cardView.getLayoutParams()).setBehavior(behavior);
}
}
Also, here are some examples of using the CoordinatorLayout:
How to use SwipeDismissBehavior.OnDismissListener on RecyclerView
CoordinatorLayout using the ViewPager's RecyclerView
https://lab.getbase.com/introduction-to-coordinator-layout-on-android/
http://android-developers.blogspot.co.uk/2015/05/android-design-support-library.html
I haven't been able to find many examples using SwipeDismissBehavior specifically, but the concepts are similar to the links above.
Alternatively, you may also be able to follow the suggestions of a similar post:
Android swipe layout to dismiss to get the results you desire.
Hope this helps.

How to save state of Fragments in ViewPager when orientation changes

I have an application that Implements ActionBarSherlock, it's mainly composed of
ViewPager with different content of fragments (for each page), with ViewPager indicator.
Here is my onCreate Method of the Activity that extends SherlockFragmentActivity
// Assume that tabs,sources,types are string arrays e.g. tabs = ["tab1","tab2","tab3"]
// types = ["listview","listview","webview"]
// according to the type of each tab, the type of content of the fragment associated to that tab is determined (e.g. WebView or ListView)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
srcContext = getBaseContext();
srcActivity = SaudiActivity.this;
int selectPos = 0;
Intent sender = getIntent();
FragmentPagerAdapter mAdapter = new NewsListAdapter(
getSupportFragmentManager());
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(mAdapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(pager);
pager.setOffscreenPageLimit(tabs.length);
pager.setCurrentItem((tabs.length - 1));
currentPosition = (tabs.length - 1);
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPosition = position;
if ((type[position] == "listview" || type[position]
.equals("listview")) && loaded[position] == false) {
loaded[position] = true;
getNews(listViews[position], position);
}
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
getSupportActionBar().setCustomView(R.layout.logo);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
Context ctx = getSupportActionBar().getThemedContext();
SourcesAdapter adapter = new SourcesAdapter(ctx,
R.layout.navigation_list_item, src_name, icons, src_value);
}
Here are my News List Adapter (that creates the fragments),
public static class MyViewHolder {
public TextView title;
public ImageView icon;
}
class NewsListAdapter extends FragmentPagerAdapter {
public NewsListAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new NewsFragment(MyActivity.this, position);
}
// This is the number of pages -- 5
#Override
public int getCount() {
return tabs.length;
}
// This is the title of the page that will apppear on the "tab"
public CharSequence getPageTitle(int position) {
return tabs[position];
}
}
public List<NewsItem> NewsItems;
Finally here's my NewsFragment:
public static class NewsFragment extends Fragment {
private int position;
public NewsFragment() {
}
public NewsFragment(Context ctx, int pos) {
this.position = pos;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
if (type[position].equals("listview")) {
// Put a ListView in the Fragment
} else {
// Put a WebView in the Fragment
}
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Let the fragment handle it's state by overriding onSaveInstanceState and placing the necessary values into outState. Recover that state in onCreateView using savedInstanceState. Also I'm pretty sure that if you're using Actionbarsherlock fragments need to extend SherlockFragment rather than Fragment.

Add / Delete pages to ViewPager dynamically

I would like to add or delete pages from my view pager dynamically. Is that possible?
Yes. You can add or delete views dynamically to the PagerAdapter that is supplying them to the ViewPager and call notifyDataSetChanged() from the PagerAdapter to alert the affected ViewPager about the changes. However, when you do so, you must override the getItemPosition(Object) of the PagerAdapter, that tells them whether the items they are currently showing have changed positions. By default, this function is set to POSITION_UNCHANGED, so the ViewPager will not refresh immediately if you do not override this method. For example,
public class mAdapter extends PagerAdapter {
List<View> mList;
public void addView(View view, int index) {
mList.add(index, view);
notifyDataSetChanged();
}
public void removeView(int index) {
mList.remove(index);
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object)) {
if (mList.contains(object) {
return mList.indexOf(object);
} else {
return POSITION_NONE;
}
}
}
Although, if you simply want to add or remove the view temporarily from display, but not from the dataset of the PagerAdapter, try using setPrimaryItem(ViewGroup, int, Object) for going to a particular view in the PagerAdapter's data and destroyItem(ViewGroup, int, Object) for removing a view from display.
Yes, since ViewPager gets the child Views from a PagerAdapter, you can add new pages / delete pages on that, and call .notifyDataSetChanged() to reload it.
Yes, the code should be like this:
public int addPage(View view, int position) {
if ((position >= 0) && (position < getSize())) {
myPagerAdapter.mListViews.add(position, view);
myPagerAdapter.notifyDataSetChanged();
return position;
} else {
return -1;
}
}
public View removePage(int position) {
if ((position < 0) || (position >= getSize()) || (getSize()<=1)) {
return null;
} else {
if (position == mPager.getCurrentItem()) {
if(position == (getSize()-1)) {
mPager.setCurrentItem(position-1);
} else if (position == 0){
mPager.setCurrentItem(1);
}
}
View tempView = myPagerAdapter.mListViews.remove(position);
myPagerAdapter.notifyDataSetChanged();
return tempView;
}
}
But there is a bug. If the current Item is 0, and to remove page 0, it will not refresh the screen instantly, I haven't found a solution for this.
Here's an alternative solution to this question. My adapter:
private class PagerAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener, TabListener {
private List<Fragment> mFragments = new ArrayList<Fragment>();
private ViewPager mPager;
private ActionBar mActionBar;
private Fragment mPrimaryItem;
public PagerAdapter(FragmentManager fm, ViewPager vp, ActionBar ab) {
super(fm);
mPager = vp;
mPager.setAdapter(this);
mPager.setOnPageChangeListener(this);
mActionBar = ab;
}
public void addTab(PartListFragment frag) {
mFragments.add(frag);
mActionBar.addTab(mActionBar.newTab().setTabListener(this).
setText(frag.getPartCategory()));
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
/** (non-Javadoc)
* #see android.support.v4.app.FragmentStatePagerAdapter#setPrimaryItem(android.view.ViewGroup, int, java.lang.Object)
*/
#Override
public void setPrimaryItem(ViewGroup container, int position,
Object object) {
super.setPrimaryItem(container, position, object);
mPrimaryItem = (Fragment) object;
}
/** (non-Javadoc)
* #see android.support.v4.view.PagerAdapter#getItemPosition(java.lang.Object)
*/
#Override
public int getItemPosition(Object object) {
if (object == mPrimaryItem) {
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) { }
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) { }
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
/**
* This method removes the pages from ViewPager
*/
public void removePages() {
mActionBar.removeAllTabs();
//call to ViewPage to remove the pages
vp.removeAllViews();
mFragments.clear();
//make this to update the pager
vp.setAdapter(null);
vp.setAdapter(pagerAdapter);
}
}
Code to remove and add dynamically
//remove the pages. basically call to method removeAllViews from ViewPager
pagerAdapter.removePages();
pagerAdapter.addPage(pass your fragment);
After the advice of Peri Hartman, it started to work after I set null to ViewPager adapter and put the adapter again after the views removed. Before this the page 0 doesn't showed its list contents.
I am sure you have created an adapter by extending PageAdapter, so there is one method:
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
For detailed example for the same, just go through this example.
First:override the pagerAdapter method "getItemPosition"
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Second:remove the data bind with the adapter.and call adapter.notifydatachanged
#Bind(R.id.pager)
ViewPager pager;
int pos = pager.getCurrentItem();
pager.removeViewAt(pos);
Based on other answers and other resources I've ended with this code.
CustomPagerAdapter:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CustomPagerAdapter extends PagerAdapter {
private List<Fragment> pages = new ArrayList<>();
private Map<Fragment, Integer> fragmentsPosition = new HashMap<>();
private Fragment currentPrimaryItem;
private FragmentManager fragmentManager;
private FragmentTransaction currentTransaction;
public CustomPagerAdapter(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
Fragment pageFragment = pages.get(position);
String tag = pageFragment.getArguments().getString(MainActivity.FRAGMENT_TAG_ARG);
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (fragment != null) {
if (fragment.getId() == container.getId()) {
currentTransaction.attach(fragment);
}
else {
fragmentManager.beginTransaction().remove(fragment).commit();
fragmentManager.executePendingTransactions();
currentTransaction.add(container.getId(), fragment, tag);
}
}
else {
fragment = pageFragment;
currentTransaction.add(container.getId(), fragment, tag);
}
if (fragment != currentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
#Override
public int getCount() {
return pages.size();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
currentTransaction.detach((Fragment) object);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment) object;
if (fragment != currentPrimaryItem) {
if (currentPrimaryItem != null) {
currentPrimaryItem.setMenuVisibility(false);
currentPrimaryItem.setUserVisibleHint(false);
}
if (fragment != null) {
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
}
currentPrimaryItem = fragment;
}
}
#Override
public void finishUpdate(ViewGroup container) {
if (currentTransaction != null) {
currentTransaction.commitAllowingStateLoss();
currentTransaction = null;
fragmentManager.executePendingTransactions();
}
}
#Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView() == view;
}
#Override
public int getItemPosition(Object o) {
Integer result = fragmentsPosition.get(o);
if (result == null) {
return PagerAdapter.POSITION_UNCHANGED;
}
return result;
}
// ---------------------------------- Page actions ----------------------------------
public void addPage(Fragment fragment) {
fragmentsPosition.clear();
pages.add(fragment);
notifyDataSetChanged();
}
public void removePage(int position) {
fragmentsPosition.clear();
Fragment pageFragment = pages.get(position);
String tag = pageFragment.getArguments().getString(MainActivity.FRAGMENT_TAG_ARG);
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (fragment != null) {
fragmentsPosition.put(fragment, PagerAdapter.POSITION_NONE);
}
for (int i = position + 1; i < pages.size(); i++) {
pageFragment = pages.get(i);
tag = pageFragment.getArguments().getString(MainActivity.FRAGMENT_TAG_ARG);
fragment = fragmentManager.findFragmentByTag(tag);
if (fragment != null) {
fragmentsPosition.put(fragment, i - 1);
}
}
pages.remove(position);
notifyDataSetChanged();
}
}
MainActivity:
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public static final String FRAGMENT_TAG_ARG = "tag";
private CustomPagerAdapter mCustomPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCustomPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager());
mCustomPagerAdapter.addPage(MainFragment.newInstance("Main_Title"));
mCustomPagerAdapter.addPage(SecondaryFragment.newInstance("Secondary_Title"));
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mCustomPagerAdapter);
}
}
To remove pages:
mCustomPagerAdapter.removePage(1);
MainFragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainFragment extends Fragment {
public static final String FRAGMENT_TAG = "MainFragment";
public static MainFragment newInstance(String text) {
return newInstance(text, FRAGMENT_TAG);
}
public static MainFragment newInstance(String text, String tag) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
args.putString("text", text);
args.putString(MainActivity.FRAGMENT_TAG_ARG, tag + "_" + fragment.hashCode());
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getArguments().getString("text"));
return rootView;
}
}
SecondaryFragment has the same code.
The layouts are simple ViewPager/Fragment layouts with android.support.v4.view.ViewPager with id container and Fragment TextView with id section_label.
Resources:
dynamically add and remove view to viewpager
How to Remove Fragment from FragmentPagerAdapter?
https://github.com/takaaki7/ArrayPagerAdapter
https://github.com/commonsguy/cwac-pager
you have to set the adapter to viewpager again, then it will refresh the content.
removeView(int pos) in my PagerAdaper
public void removeView(int index) {
imageFileNames.remove(index);
notifyDataSetChanged();
}
wherever I am removing the file I have to do like this
imagePagerAdapter.removeView(currentPosition);
viewPager.setAdapter(imagePagerAdapter);
EDIT:
This below method is effective, you can apply the below one.
public void updateView(int pos){
viewPager.setAdapter(null);
imagePagerAdapter =new ImagePagerAdapter(YOUR_CONTEXT,YOUR_CONTENT);
viewPager.setAdapter(imagePagerAdapter);
viewPager.setCurrentItem(pos);
}
replace YOUR_CONTEXT with your context and your content with your content name i.e. updated list or something.

Categories

Resources