I cant call a method In ViewPager from RecyclerView adapter - android

I whan to call a method that adds respective fragment to viewpager whenever user click on item from recyclerview. how can i do it??, below is my code. thanks
SemesterFragmentViewPager.java
public SemesterFragmentViewPager() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_semester, container, false);
viewPager2 = (ViewPager2) view.findViewById(R.id.viewPager2);
tabLayout = view.findViewById(R.id.tabLayout);
adapter = new MyViewPager(getChildFragmentManager(), this.getLifecycle());
viewPager2.setAdapter(adapter);
new TabLayoutMediator(tabLayout, viewPager2,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Sem" + (position + 1));
}
}).attach();
// addComputerScienceSem();
// cs();
adapter.notifyDataSetChanged();
return view;
}
public void addComputerScienceSem() {
adapter.addFrags(Semesters.newInstance(0, 0));
adapter.addFrags(Semesters.newInstance(0,1));
adapter.addFrags(Semesters.newInstance(0,2));
adapter.addFrags(Semesters.newInstance(0,3));
}
public void cs(){
adapter.addFrags(Semesters.newInstance(0,4));
adapter.addFrags(Semesters.newInstance(0,5));
}
}
what i want to achieve below is that when ever the case is 0 then i should call cs() method from SemesterFragmentViewPager.java, but not working why
DepartmentRVAdapter.java
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imgDepLogo = itemView.findViewById(R.id.imgDeptLogo);
tvDepName = itemView.findViewById(R.id.tvDepName);
tvDepName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickInterface.onItemClickListener(getLayoutPosition());
switch (getAdapterPosition()){
case 0:
Objects.requireNonNull(departmentFragment.getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout,new SemesterFragmentViewPager().cs())// it couldnt work
.addToBackStack(null).
commit();
break;
and when the case is 1 then i should call addComputerScienceSem() method from SemesterFragmentViewPager.java, but not working
case 1:
Objects.requireNonNull(departmentFragment.getActivity()).getSupportFragmentManager()
.beginTransaction()
// .setCustomAnimations(R.anim.slide_in_left,R.anim.exit_to_left,R.anim.enter_from_right,R.anim.exit_to_left)
.replace(R.id.frameLayout, new SemesterFragmentViewPager().addComputerScienceSem())// it couldnt work too
.addToBackStack(null).
commit();
break;
MyViewPager.java
public class MyViewPager extends FragmentStateAdapter {
List<Fragment> fragmentList = new ArrayList<>();
public MyViewPager(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
return fragmentList.get(position);
}
#Override
public int getItemCount() {
return fragmentList.size();
}
public void addFrags(Fragment fragment){
fragmentList.add(fragment);
}
}

Step 1: You should create Callback (Interface)
interface HandleClickItemsRecycleview{
void onclickItemRecycleView()
}
And set to Adapter Recycleview Constructor
Step 2: Implement Callback with SemesterFragmentViewPager
SemesterFragmentViewPager implement HandleClickItemsRecycleview
Function Overide
void onClickItemRecyleview(){
// Action Add Fragment To ViewPager.
}
Concerning the response to the above recycleview item click event handling
. Hope it is useful to you

Related

Replacing Fragment inside ViewPager from Fragment RecycerView Adapter Return Blank Screen?

I am trying to replace the current active fragment inside ViewPager when item inside fragment's recycelerview is clicked. So far, I manage to pop up the Toast on the second fragment when the item on the first fragment is clicked, but the all the view of the second fragment is blank.
Here is my code:
MainActivity.class
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.view_pager);
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(adapter.getCount() - 1);
}
// ..........
private static class FragmentAdapter extends FragmentStatePagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return AllGenreFragment.newInstance();
case 1:
return DashboardFragment.newInstance();
case 2:
return NotificationFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
// ..........
}
AllGenreFragment.class
public class AllGenreFragment extends Fragment {
RecyclerView genreRV;
private AllGenreAdapter allGenreAdapter;
private List<Genre> genreList;
public static AllGenreFragment newInstance() {
return new AllGenreFragment();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_genre, container, false);
genreRV = v.findViewById(R.id.rv);
genreRV.setHasFixedSize(true);
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
genreRV.setLayoutManager(layoutManager);
genreList = new ArrayList<>();
allGenreAdapter = new AllGenreAdapter(genreList, getContext());
genreRV.setAdapter(allGenreAdapter);
return v;
}
}
AllGenreAdapter.class
public class AllGenreAdapter extends RecyclerView.Adapter<AllGenreAdapter.ViewHolder> {
// .......
class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
public ViewHolder(final View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Genre: " + genre_title.getText().toString(), Toast.LENGTH_SHORT).show();
AppCompatActivity activity = (AppCompatActivity) itemView.getContext();
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment allAnimeFragment = new AllAnimeFragment();
Bundle bundle = new Bundle();
bundle.putString("genreid", genre_id.getText().toString().trim());
allAnimeFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.view_pager, allAnimeFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
}
// .......
}
AllAnimeFragment.class
public class AllAnimeFragment extends Fragment {
RecyclerView animeRV;
private AllAnimeAdapter allAnimeAdapter;
private List<Anime> animeList;
String genreid;
public static AllAnimeFragment newInstance() {
return new AllAnimeFragment();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_anime, container, false);
Bundle arguments = getArguments();
genreid = arguments.getString("genreid");
Toast.makeText(getContext(), genreid, Toast.LENGTH_SHORT).show();
// .....
return v;
}
}
Your approach is not really good, try below way:
Create a container fragment, called ContainerFragment, example, you will be using this fragment for your ViewPager.
The ContainerFragment should contain a container view, and add AllGenreFragment in the first them it is invoked.
In AllGenreFragment, create a callback, when an item in the RecyclerView be clicked, then in ContainerFragment will replace (or add) current fragment (AllGenreFragment) to AllAnimeFragment
First, create ContainerFragment,
public class ContainerFragment extends Fragment implements AllGenreFragment.OnAllGenreFragmentListener {
#Nullable #Override public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_container, container, false);
}
#Override public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initialLoad();
}
private void initialLoad() {
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, AllGenreFragment.newInstance())
.commit();
}
#Override public void onItemClicked() {
getChildFragmentManager()
.beginTransaction()
.replace(R.id.container, AllAnimeFragment.newInstance())
.commit();
}
}
This Fragment should implement a callback from AllGenreFragment for handling fragment transaction.
also, the xml layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Next step, add above fragment into ViewPager, we using ContainerFragment instead of AllGenreFragment.
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ContainerFragment().newInstance();
case 1:
return DashboardFragment.newInstance();
case 2:
return NotificationFragment.newInstance();
}
return null;
}
Ok, so now come back to AllGenreFragment, we should create a CallBack that we implement in ContainerFragment
public interface AllGenreFragmentListener {
onItemClicked();
}
and then,
private AllGenreFragmentListener listener;
#Override public void onAttach(Context context) {
super.onAttach(context);
if (getParentFragment() instanceof AllGenreFragmentListener) {
listener = (AllGenreFragmentListener) getParentFragment();
}
}
so we have an instance of AllGenreFragmentListener, from now, whenever listener call onItemClicked, the method onItemClicked in ContainerFragment will be invoked.
Ok, let do it,
create below variable and method in your AllGenreAdapter:
private AllGenreFragmentListener listener;
public void setListener(AllGenreFragmentListener listener) {
this.listener = listener;
}
and update your ViewHodler
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Genre: " + genre_title.getText().toString(), Toast.LENGTH_SHORT).show();
if (listener != null)
listener.onItemClicked()
});
}
Don't forget call setListener method in your AllGenreFragment, so please add
#Override public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (allGenreAdapter != null) allGenreAdapter.setListener(listener);
}
That all,
I type this code by hand, not in my IDE so maybe it not compile, so please fix it if you face any compile error.
Note
If you want to keep the behavior of the BACK button, override onBackPressed in your MainActivity
#Override public void onBackPressed() {
Fragment f = getCurrentFragment();
if (f != null) {
if (f.getChildFragmentManager().getBackStackEntryCount() > 1) {
f.getChildFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}
public Fragment getCurrentFragment() {
return (Fragment) viewPager.getAdapter()
.instantiateItem(viewPager, viewPager.getCurrentItem());
}
Also, add fragment into backStack whenever we add them to the container view (in your ContainerFragment)
private void initialLoad() {
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, AllGenreFragment.newInstance())
.addToBackStack(null)
.commit();
}
#Override public void onItemClicked() {
// change `replace` to `add` and add more `.addToBackStack(null)`
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, AllAnimeFragment.newInstance())
.addToBackStack(null)
.commit();
}
you should add a context in the constructor of your adapter
public class AllGenreAdapter(Context context) extends RecyclerView.Adapter<AllGenreAdapter.ViewHolder> {
// .......
}
then pass your activity to your adapter, use it to replace your fragment

Refresh Fragment in FragmentActivity

My app have a fragmentActivity with tabBar which control over the view pager and contain 3 fragments ,when i update my class User in fragmentB,i need to display him in fragmentC.
my question is how to refresh fragmentC every time when i add new User.
before i wrote this question i tried all the solution from this questions:
1.Update ViewPager dynamically?
2.refresh fragment at reload
3.Update Fragment from ViewPager
4.ViewPager PagerAdapter not updating the View
5.How to update fragment content from activity (viewpager)?
here is my code
FragmentActivity:
public class MainActivityTab extends FragmentActivity {
public SectionsPagerAdapter mSectionsPagerAdapter;
public ViewPager mViewPager;
public static MainActivityTab instance = null;
public static MainActivityTab getInstance(){
return instance;
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tab);
getWindow().setStatusBarColor(Color.rgb(191,76,12));
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_A);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_B);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_C);
mViewPager.setCurrentItem(1,false);
}
FragmentStatePagerAdapter:
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return FragmentA.newInstance();
case 1:
return FragmentA.newInstance();
case 2:
return FragmentC.newInstance();
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return null;
}
}
FragmentB:
public class FragmentB extends Fragment {
EditText name;
EditText age;
Button btnSave;
public static FragmentB newInstance() {
FragmentB fragment = new FragmentB();
return fragment;
}
public FragmentB() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new2, container, false);
name = (EditText) rootView.findViewById(R.id.name);
age = (EditText) rootView.findViewById(R.id.age);
btnSave = (Button) rootView.findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserManager.getInstance().creteUser(name.getText().toString(),age.getText().toString());
}
});
return rootView;
}
}
FragmentC:
public class FragmentC extends Fragment {
TextView nameTxt;
TextView ageTxt;
public static FragmentC newInstance(){
FragmentC instance = new FragmentC();
return instance;
}
public FragmentC(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new3, container, false);
nameTxt = (TextView) rootView.findViewById(R.id.nameTxt);
ageTxt = (TextView) rootView.findViewById(R.id.ageTxt);
showUser();
return rootView;
}
public void showUser(){
if(UserManager.getInstance().getUser().getName()!=null){
nameTxt.setText(UserManager.getInstance().getUser().getName().toString());
ageTxt.setText(UserManager.getInstance().getUser().getAge().toString());
}
}
}
You could create a callback like:
public interface UserChangedCallback{
void onUserChanged();
}
and implement this callback on every view/fragment where you want to access the user:
#Override
public void onUserChanged() {
adapter.notifyDataSetChanged();
// or if you don't have an adapter refresh your textfields or whatever you want
}
Register the callback on the usermanager via UserManager.getInstance().registerCallback(this). Internally the usermanager have to add the callback to an internal list.
Create a private function inside your usermanager:
private void notifyCallbacks() {
for(UserChangedCallback callback : registeredCallbacks) {
callback.onUserChanged();
}
}
If you add/modify/delete a user you always have to call this function at the end. For example:
public void addUser(User user) {
users.add(user);
notifiCallbacks();
}
Now every view will be notified and refreshed.
Important!
Don't forget to unregister the callback from the usermanager on onDestroy() to avoid memory leaks.
Found solution:
i used in the method onPageSelected,when position is 2 my fragment detach and afterwards attach the fragment.
working perfectly!
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(position==2){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().add(R.id.fragmant_new3, FragmentC.newInstance());
fragmentTransaction.detach(FragmentC.newInstance());
fragmentTransaction.attach(FragmentC.newInstance());
fragmentTransaction.commit();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

View pager skipping to irregular position when I click button in second fragment android?

I am using view pager in activity and the sequence is - when I click the next button in first page, it should go to the second page. If I click the button in second page, it should go to third and so on. But my current app is behaving weird, i.e, When I click next button in second page, it goes to fourth page. Once again when I click first button in first page, it jumps to third page and so on..
Here is code.
public class ViewPagerActivity extends AppCompatActivity {
private ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_act);
setViewPager();
/*pager.setPageTransformer(true, new ZoomPageTransformer());
pager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));
pager.post(new Runnable() {
#Override
public void run() {
pager.setCurrentItem(position); //don't know how to use this from fragment
}
});*/
}
private void setViewPager() {
pager = (ViewPager) findViewById(R.id.viewPager);
FragmentManager fm = getSupportFragmentManager();
ViewPagerAdapter adapter = new ViewPagerAdapter(fm);
pager.setAdapter(adapter);
}
public void setCurrentItem(int selectedPosition) {
pager.setCurrentItem(selectedPosition, true);
}
private class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FirstPager.newInstance();
case 1:
return SecondPager.newInstance();
case 2:
return ThirdPager.newInstance();
case 3:
return FourthPager.newInstance();
case 4:
return FifthPager.newInstance();
case 5:
return SixthPager.newInstance();
default:
return null;
}
}
#Override
public int getCount() {
return 6;
}
}
FirstPager:
public class FirstPager extends Fragment {
private ImageView slideArrow;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_pager, container, false);
return v;
}
public static FirstPager newInstance() {
FirstPager fragment = new FirstPager ();
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initUI();
}
private void initUI() {
slideArrow = (ImageView) getActivity().findViewById(R.id.next_arrow);
slideArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((ViewPagerActivity)getActivity()).setCurrentItem (1);
}
});
}
}
Similarly in other fragments, I gave currentItem as 2,3,4,5 and 6. But it’s position behavior is not correct.
I referred some post but how in my case, how I will apply for a method to pass from fragment to make the position to work correctly?
I think the best approach would be this:
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
slideArrow = (ImageView) getActivity().findViewById(R.id.next_arrow);
Are you sure, you're calling this correctly? You're not.
You're calling findViewById of the arrow inside your activity. A ViewPager works by loading this page, and pre-loading next and previous pages for smooth swipe. And when you click the button on your 1st page, the last loaded page's (in your case 2nd page's) button click event gets called.
You must use the arrow button in each of your fragments
You can do something like this:
public class FirstPager extends Fragment {
private ImageView slideArrow;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.first_pager, container, false);
return v;
}
public static FirstPager newInstance() {
FirstPager fragment = new FirstPager ();
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initUI();
}
private void initUI() {
slideArrow = (ImageView) v.findViewById(R.id.next_arrow); // Note the difference in this line.
slideArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((ViewPagerActivity)getActivity()).setCurrentItem (1);
}
});
}
}
You can do two things here:
Firstly,Your viewpager has a override method onPageSelected() which return the select page positon. using this poistion element get the view and bind your button there and write listener there itself and write viewpager.setCurrentItem(i++); //if i is ur current position,but be sure to check if it is the last item.
secondly,you hold the position of the current fragment and
((ViewPagerActivity)getActivity()).setCurrentItem (next_frag_pos);
This code try working perfect.
public class ViewPagerActivity extends FragmentActivity {
private ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_act);
setViewPager();
/*pager.setPageTransformer(true, new ZoomPageTransformer());
pager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));
pager.post(new Runnable() {
#Override
public void run() {
pager.setCurrentItem(position); //don't know how to use this from fragment
}
});*/
}
private void setViewPager() {
pager = (ViewPager) findViewById(R.id.viewPager);
FragmentManager fm = getSupportFragmentManager();
ViewPagerAdapter adapter = new ViewPagerAdapter(fm);
pager.setAdapter(adapter);
}
public void setCurrentItem(int selectedPosition) {
pager.setCurrentItem(selectedPosition, true);
}
private class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirstPager();
case 1:
return new SecondPager();
case 2:
return new ThirdPager();
case 3:
return new FourthPager();
case 4:
return new FifthPager();
case 5:
return new SixthPager();
default:
return null;
}
}
#Override
public int getCount() {
return 6;
}
}
}

getItem in FragmentStatePagerAdapter never called when instantiating from a Fragment

I'm using a Fragment on my Activity that will have a picture "swiper". I've created a FragmentStatePagerAdapter which I'm trying to call from this Fragment and for some reason my getItem() method is never being called.
I've searched and found that I need to use getChildFragmentManager() when instantiating my FragmentStatePagerAdapter because I'm calling it from a Fragment. I've tried this as well as getSupportFragmentManager() with no luck from either.
Any ideas?
here's my Fragment that I'm using on my MainActivity with the method that shoudl setup the FragmentStatePagerAdapter:
public class PhotoFlipper extends Fragment {
// properties and fields
// primitive types
String currentImage;
int friendShareType = 0;
ImageView share;
ViewPager pager;
PhotoFlipperItemAdapter pagerAdapter;
LatLng itemPosition;
Activity activity;
FragmentActivity fragActivity;
public ArrayList<MarkerModel> picsAndVids;
// end properties and fields
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View photoFlipperFragmentView = inflater.inflate(R.layout.photo_flipper_layout, container, false);
InitializeFragment(photoFlipperFragmentView);
return photoFlipperFragmentView;
}
private void InitializeFragment(View photoFlipperFragmentView) {
activity = getActivity();
fragActivity = (FragmentActivity)activity;
pager = (ViewPager)photoFlipperFragmentView.findViewById(R.id.photoflipper_pager);
share = (ImageView)photoFlipperFragmentView.findViewById(R.id.photoflipper_share);
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IPictureFlipper iPictureFlipper = (IPictureFlipper)activity;
iPictureFlipper.ShareVideoOrImage(friendShareType, itemPosition, currentImage);
}
});
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
pager.setVisibility(View.GONE);
}
}
public void SetTappedPicture(int index) {
pagerAdapter = new PhotoFlipperItemAdapter(getChildFragmentManager(), picsAndVids, picsAndVids.size());
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(index);
pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
}
});
}
}
And here's my FragmentStatePagerAdapter:
public class PhotoFlipperItemAdapter extends FragmentStatePagerAdapter {
ArrayList<MarkerModel> _markers;
int NUM_PAGES;
String TAG = "home";
public PhotoFlipperItemAdapter(FragmentManager fm, ArrayList<MarkerModel> markers, int numpages){
super(fm);
Log.d(TAG,"in adapter in constructor");
_markers = markers;
NUM_PAGES = numpages;
}
#Override
public Fragment getItem(int position) {
Log.d(TAG,"in adapter in get item");
Fragment fragment = PhotoFlipperItemFragment.create(position, _markers);
return fragment;
}
#Override
public int getCount() {
Log.d(TAG,"in adapter in get count: "+NUM_PAGES);
return NUM_PAGES;
}
}
logcat is showing me that NUM_PAGES is > 0 so that's not my issue. I see my log in the constructor and in getCount() but nothing in getItem().
TIA
I got this sorted out. I was hiding my fragment in my InitializeActivity() right after I added it to my FragmentManager so it was never fully building the Fragment with the ViewPager etc.
I'm going to have to come up with a different solution for hiding/showing the fragment but that was my problem.

PagerAdapter not called inside fragment when I move to the fragment for the second time in Android

I'm working with viewpager inside fragments. I'm using pagerAdapter to switch between two pages via XML. Here is the code:
public class DemoPagerAdapter extends FragmentPagerAdapter {
public DemoPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
Fragment f;
switch (index) {
case 0:
f = new FirstFragment();
break;
case 1:
f = new SecondFragment();
break;
}
return f;
}
#Override
public int getCount() {
return 2;
}
}
And I'm calling it like this:
public class DemoFragment1 extends Fragment {
private ViewPager viewPager;
private DemoPagerAdapter mAdapter;
public DemoFragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.security, container, false);
mAdapter = new DemoPagerAdapter(getActivity().getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
showPages(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
return rootView;
}
Everything works fine. But if I move to DemoFragment2 and then come back to DemoFragment1, PagerAdapter is not called.
Your ViewPager is nested in a Fragment, you should use the ChildFragmentManager, modify:
mAdapter = new DemoPagerAdapter(getChildFragmentManager());
I also assume the ViewPager will keep the off screen fragment in memory, thus it might not call getItem(int index) again. Add
viewPager.setOffscreenPageLimit(0);
return rootView;
Well, I encontered this issue last week.
When I put the ViewPager in the fragment with a FragmentPagerAdapter, after I move forward to anoter Fragment and back, the pager' s view not exists.
I supposed is the FragmentPagerAdapter won' t retain its view in the ViewPager ' s host Fragment, Their life cycle is not the same. Though you put the VewPager' s host Fragment in the back stack, but the FragmentPagerAdapter' s fragment not. And Then, I gave up FragmentPagerAdapter and tried android.support.v4.view.PagerAdapter, (note, it wont' t use fragment to inject view!), everything is fine!
below is the sample:
private final PagerAdapter coverPager = new PagerAdapter() {
private LayoutInflater mLayoutInflater;
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
if (mLayoutInflater == null) {
mLayoutInflater = LayoutInflater.from(getActivity());
}
switch (position) {
case 0:
View frontPage = mLayoutInflater.inflate(R.layout.profile_cover, container, false);
ImageView avatar = (ImageView) frontPage.findViewById(R.id.avatar);
Picasso.with(getActivity())
.load(mAvatarUrl)
.placeholder(R.drawable.error)
.error(R.drawable.error)
.into(avatar);
TextView screenName = (TextView) frontPage.findViewById(R.id.screen_name);
screenName.setText("#" + mScreenName);
TextView remark = (TextView) frontPage.findViewById(R.id.remark);
remark.setText(TextUtils.isEmpty(mRemark) ? mScreenName : mRemark);
if (mVerified) {
frontPage.findViewById(R.id.verified).setVisibility(View.VISIBLE);
}
container.addView(frontPage);
return frontPage;
case 1:
View introPage = mLayoutInflater.inflate(R.layout.profile_intro, container, false);
CatnutUtils.setText(introPage, R.id.description, TextUtils.isEmpty(mDescription)
? getString(R.string.no_description) : mDescription);
CatnutUtils.setText(introPage, R.id.location, mLocation);
CatnutUtils.setText(introPage, R.id.profile_url, Constants.WEIBO_DOMAIN + mProfileUrl);
container.addView(introPage);
return introPage;
default:
return null;
}
}
};
and then in your onViewCreate or OnCreateView, put mViewPager.setAdapter(coverPager);
the instantiateItem is the place to put the page' s view, similar like the FragmentPagerAdapter!
It' s just like put the FragmentAdapter' s view int the ViewPager' s host Fragment, not the other fragment!
Hope it' s helpful!

Categories

Resources