Refresh fragment in ViewPager - java

I have ViewPager that has 3 tabs. Tab(3), beside stock fragment, includes 2 more fragments (B) --> (C).
Tab(1)
Tab(2)
Tab(3) --> (B) --> (C)
By pressing a button in (C) I want to refresh/recreate Tab(2).
What's the best way to do it? Thank you.
public class ViewPageAdapter extends FragmentStatePagerAdapter {
private static int NUM_ITEMS = 3;
private FragmentManager mFragmentManager;
private Context mContext;
public ViewPageAdapter(#NonNull FragmentManager fm, Context context) {
super(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mFragmentManager = fm;
mContext = context;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new FragmentInsta();
case 1: return new FragmentListUnlogged();
case 2: return new FragmentHostUnlogged();
default:
return new FragmentListLogged();
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
}

Thanks to user named "Andrew" I found the solution.
I override the onPause method in this way.
#Override
public void onResume() {
if(preferenceUtils.getBoolean("isLogged")){
FragmentTransaction trans = getChildFragmentManager().beginTransaction();
trans.replace(R.id.listUnlogged_container, new FragmentListLogged(), "ListUnlogged-ListLogged");
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(FRAGMENT_TAG);
trans.commit();
}
super.onResume();
}

Related

Context in ViewPager

I store information if user is logged in SharedPreferences.
In my ViewPager adapter I want to check if userIsLoggedIn. Depending on that I will display different fragments.
My question is: in order to get data from sharedPreferences I need a context. How do I get it from my ViewPager adapter class?
Thank you.
public class ViewPageAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
private FragmentManager mFragmentManager;
public ViewPageAdapter(#NonNull FragmentManager fm) {
super(fm);
mFragmentManager = fm;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return new FragmentInsta();
case 1: return new FragmentList();
case 2: return new FragmentHostUnlogged();
default:
return new FragmentList();
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public int getItemPosition(#NonNull Object object) {
if (object instanceof FragmentHostUnlogged)
return POSITION_NONE;
return POSITION_UNCHANGED;
}
}
You should use FragmentStatePagerAdapter . FragmentPagerAdapter is deprecated.
class ViewPageAdapter extends FragmentStatePagerAdapter {
Context context;
ViewPagerAdapter(FragmentManager manager,Context c) {
super(manager,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
context=c;
}
Read Context from official guideline.
Interface to global information about an application environment. This
is an abstract class whose implementation is provided by the Android
system.
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), getApplicationContext());

How to hide fragment from activity - Android Studio

I have two fragment in one activity, and I need to know how to just hide the second fragment and leave the firs one
So, i want to hide PerfilDatosFragmen();, but i also need to keep "2" in return statement. how can i do that?
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
String[] encabezado = {"Tarjeta", "Datos"};
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new PerfilTarjetaFragment();
case 1:
return new PerfilDatosFragmen();
}
return null;
}
#Override
public int getCount() {
System.out.println(vacio);
// int vacio = getIntent().getExtras().getInt("AcompaƱante");
/* if(vacio.equals("1")){
a= 1;
}else{
a= 2;
}*/
return 2;
}
It's very simple. PagerAdapter.getCount() is defined the count of your fragments. You always return 2. The best solution is:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> fragments = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
fragments.add(new PerfilTarjetaFragment());
fragments.add(new PerfilDatosFragmen());
}
String[] encabezado = {"Tarjeta", "Datos"};
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}

How to refresh fragment in FragmentPagerAdapter

I Have 4 Fragments in 1 Activity. I need to make sure that on every fragment change the fragment is refreshed because I load JSON Data in every fragment. I use FragmentPager Adapter and RecyclerView to Show Data
This is my Adapter ( SickAdapter.java ) the code :
public class SickAdapter extends FragmentPagerAdapter{
private static final String TAG = SickAdapter.class.getSimpleName();
private static final int FRAGMENT_COUNT = 4;
public SickAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new SickFragmentToAll();
case 1:
return new SickFragmentToPending();
case 2:
return new SickFragmentToApproved();
case 3:
return new SickFragmentToDenied();
}
return null;
}
#Override
public int getCount() {
return FRAGMENT_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "All";
case 1:
return "Pending";
case 2:
return "Approved";
case 3:
return "Denied";
}
return null;
}
}
In my Class ( SickClass.java ) I create SickClass and I Call SickAdapter, I explode them, and this is my Code :
public class SickClass extends Fragment {
private static final String TAG = SickClass.class.getSimpleName();
private SickAdapter mAdapter;
private TabLayout tabLayout;
private ViewPager viewPager;
public SickClass() {
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.employee_leave_class, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
viewPager = (ViewPager)view.findViewById(R.id.view_pager);
if(mAdapter == null) {
mAdapter = new SickAdapter(getChildFragmentManager());
}
viewPager.setAdapter(new SickAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1, true);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
}
Try below code for reload your fragment;
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(YOUR_FRAGMENT_NAME.this).attach(YOUR_FRAGMENT_NAME.this).commit();
You can use startActivityForResult() to get the result from the activity.
References:
ViewPager PagerAdapter not updating the View
How to refresh a Fragment of a FragmentPagerAdapter?

Not calling before fragment is shown

I'm showing fragments in viewpager, and each fragment contains data connection.
I don't want to do something, before selected fragment is shown.
How can I do?
I mean, I don't want to initiate fragments when the activity calls oncreate.(because there's data connection, and I don't want it)
I just want to initiate each fragment, when fragment is selected.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewPager = (ViewPager) findViewById(R.id.view_pager);
List<Fragment> listFragments = new ArrayList<>();
listFragments.add(new Fg_1());
listFragments.add(new Fg_2());
listFragments.add(new Fg_3());
listFragments.add(new Fg_4());
listFragments.add(new Fg_5());
listFragments.add(new Fg_6());
a_pagerAdapter = new A_PagerAdapter(getSupportFragmentManager(), listFragments);
viewPager.setAdapter(a_pagerAdapter);
viewPager.addOnPageChangeListener(this);
}
Instead of creating all of your fragments in your activity onCreate, have your viewPager create them when requested, so for a simple example:
in your implementation of A_PagerAdapter, override getCount() and getItem(int) to be something like:
public class A_PagerAdapter extends FragmentPagerAdapter {
...
private final static int NUM_PAGES = 6;
private final Fragment[] listFragment = new Fragment[NUM_PAGES];
...
public int getCount() {
return NUM_PAGES;
}
...
public Fragment getItem(int index) {
Fragment itemFragment = null;
if (listFragment[index] == null) {
// Hard-coded class factory.. yuck.
switch(index) {
case 0:
itemFragment = new Fg_1();
break;
case 1:
itemFragment = new Fg_2();
break;
case 2:
itemFragment = new Fg_3();
break;
case 3:
itemFragment = new Fg_4();
break;
case 4:
itemFragment = new Fg_5();
break;
case 5:
itemFragment = new Fg_6();
break;
}
// Save this instance in case it is asked for again later..
listFragment[index] = itemFragment;
} else {
// get the fragment we created earlier to avoid re-initializing
itemFragment = listFragment[index];
}
return itemFragment;
}
...
This is a fairly simple/horrible implementation.. in reality it sounds more like you need a caching/lazy loading strategy, possibly triggered in the onResume of the fragments in your view pager..
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener {
final int PAGE_COUNT = 5;
private String tabTitles[] = new String[] { "Chats", "Groups", "Contacts","Profile" ,"Settings"};
public SampleFragmentPagerAdapter() {
super(getSupportFragmentManager());
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public Fragment getItem(int position) {
// return PageFragment.create(position + 1);
switch (position) {
case 0:
ChatScreenActivity chatScreenActivity = new ChatScreenActivity();
return chatScreenActivity;
case 1:
GroupChatActivity groupChatActivity = new GroupChatActivity();
return groupChatActivity;
case 2:
ContactsActivity contactsActivity = new ContactsActivity();
return contactsActivity;
case 3:
ProfileActivity profileActivity= new ProfileActivity();
return profileActivity;
case 4:
SettingActivity settingActivity = new SettingActivity();
return settingActivity;
default:
return null;
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}*use this code and do setadapter for your viewpager*
}

ViewPage - Change the icon on the text

I faced with a problem I can not solve. How can you replace icons in the text resource. Let's say instead of the first icons - current , the second icon - finished .
public class ViewPageAdapter extends FragmentPagerAdapter implements PagerSlidingTabStrip.CustomTabProvider {
private Context mContext;
private final int[] ICONS = {
R.drawable.selector_icon_active,
R.drawable.selector_icon_inactive
};
public ViewPageAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public void tabUnselected(View view) {
view.setSelected(false);
}
#Override
public void tabSelected(View view) {
view.setSelected(true);
}
#Override
public View getCustomTabView(ViewGroup parent, int position) {
FrameLayout customLayout = (FrameLayout) LayoutInflater.from(mContext).inflate(R.layout.custom_tab, parent, false);
((ImageView) customLayout.findViewById(R.id.image)).setImageResource(ICONS[position]);
return customLayout;
}
#Override
public CharSequence getPageTitle(int position) {
// return null;
return super.getPageTitle(position);
}
#Override
public int getCount() {
return ICONS.length;
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
switch (position) {
case 0:
default:
bundle.putSerializable("TYPE", NotificationsType.ACTIVE);
break;
case 1:
bundle.putSerializable("TYPE", NotificationsType.INACTIVE);
break;
}
Fragment fragment = new TabFragment();
fragment.setArguments(bundle);
return fragment;
}
}

Categories

Resources