ViewPager does not scroll fragments - android

ViewPager does not scroll fragments:
I include ViewPager inside activity.
And create two fragments, but when i scroll view pager (horizintal) only 1rst Framgent selects:
_pageAdapter=new PagerAdapter(getSupportFragmentManager());
_viewPager= (ViewPager) findViewById(R.id.viewPager);
_viewPager.setAdapter(_pageAdapter);
_viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d(LOG_TAG,"!Page #"+position);
}
}
#Override
public void onPageScrollStateChanged(int state) {
if(state==0)
Log.d(LOG_TAG,"Page Iddle");
else if(state==1)
Log.d(LOG_TAG,"Page Dragging");
else if(state==2)
Log.d(LOG_TAG,"Page Settling");
}
});
Here code of PageAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position) {
case 0: {
fragment = new FirstFramgent();
Bundle bundle = new Bundle();
bundle.putInt("num", 0);
fragment.setArguments(bundle);
break;
}
case 1: {
fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putInt("num", 1);
fragment.setArguments(bundle);
break;
}
}
return fragment;
}
#Override
public int getCount() {
return 1;
}
}
Tell me, how to make ViewPager scrolls two fragments.

Try this change:
#Override
public int getCount() {
return 2;
}

Related

Fragment onCreateView getting called multiple time so that new instance of fragment is created every time

I am trying to add the fragments on page change of view pager. but every time when i scroll the view pager, new instant of fragment is created.
public void initializeViewPager(int currentPage, String selectedCardNumber) {
currentPosition = currentPage;
FragmentPagerAdapter journeyViewPagerAdapter =
new ViewPagerAdapter(getSupportFragmentManager());
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Default Implementation
}
#Override
public void onPageSelected(int position) {
currentPosition = position;
addFragments(position, selectedCardNumber);
handleScrollState();
}
#Override
public void onPageScrollStateChanged(int state) {
//Default Implementation
}
};
viewPager.addOnPageChangeListener(onPageChangeListener);
initCarousalAdapter();
}
addFragments() method
private void addFragments(int position, final String selectedCardNumber) {
FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putInt(ApplicationConstants.SELECTED__TYPE, position);
bundle.putString(DataConstants.SELECTED__NUMBER, selectedCardNumber);
switch (position) {
case 1:
OffersFragmentOne fragment = OffersFragmentOne.getInstance();
fragment.setArguments(bundle);
fragTransaction.replace(R.id.btmt_fragment_container, fragment);
break;
case 2:
OffersFragmentTwo mtFragment = OffersFragmentTwo.getInstance();
mtFragment.setArguments(bundle);
fragTransaction.replace(R.id.btmt_fragment_container, mtFragment);
break;
case 3:
OffersFragmentThree poFragment = OffersFragmentThree.getInstance();
poFragment.setArguments(bundle);
fragTransaction.replace(R.id.btmt_fragment_container, poFragment);
break;
default:
//Default Implementation
}
fragTransaction.commit();
}
getInstance() method
private static OffersFragmentOne offersFragmentOne;
public static OffersFragmentOne getInstance() {
if (OffersFragmentOne == null) {
offersFragmentOne = new OffersFragmentOne();
}
return offersFragmentOne;
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final int[] carousalImages = {R.drawable.ic_po_carousal_banner,
R.drawable.ic_bt_carousal_banner,
R.drawable.ic_mt_carousal_banner, R.drawable.ic_po_carousal_banner,
R.drawable.ic_bt_carousal_banner};
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
CarousalFragment frag = new CarousalFragment();
CarousalFragmentPresenter.createAndAttach(frag, carousalImages[position]);
return frag;
}
#Override
public int getCount() {
return carousalImages != null ? carousalImages.length : 0;
}
}
You should write your switch case in getItem and don't required bundle and fragment transaction because getItem itself returns selected Fragment and will bind with ViewPager
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
CarousalFragment();
break;
case 1:
OffersFragmentOne.getInstance();
break;
case 2:
OffersFragmentTwo.getInstance();
break;
case 3:
OffersFragmentThree.getInstance();
break;
default:
//Default Implementation
}
}
OnPageChangeListener just give you the position of selected and scrolled item or fragment, so don't required to add fragment from onPageSelected
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Default Implementation
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
//Default Implementation
}
};
How about creating the fragment instances in the container activity or so of the view pager? That way they should be created only when the container is created.
EDIT: Adding example code.
Example:
public class ContainerActivity extends AppCompatActivity {
private FragmentOne fragmentOne;
private FragmentTwo fragmentTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.container_with_view_pager);
fragmentOne = FragmentOne.getInstance();
fragmentTwo = FragmentTwo.getInstance();
ViewPager viewPager = findViewById(R.id.viewpager);
setupViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(fragmentOne, "Fragment One");
adapter.addFragment(fragmentTwo, "Fragment Two");
viewPager.setAdapter(adapter);
}
}

TabLayout addOnTabSelectedListener is not working properly when I reopen the application

I am working with TabLayout which shows tab icon red according to fragment selected in ViewPager. But I have been facing this problem for 2 weeks and I have been searching a lot to resolve this issue.
The problem is if I am at fragment user account and when I close the application, my user tab icon is selected. Now when I reopen the application fragment, my tab restaurant is loaded, but the user account tab icon is still selected, although restaurant tab icon should be selected.
I have attached screenshots for reference:
user account image
restaurant image after re open
public class PagerMainActivity extends Fragment {
//This is our tablayout
public TabLayout tabLayout;
public static CustomViewPager viewPager;
AdapterPager adapter;
public int tabIconColor_Selected;
public int tabIconColor_DeSelected;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// tabSelection();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_pager, container, false);
tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
viewPager = v.findViewById(R.id.pager);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.restaurent).setText("Restaurant"));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.order).setText("Order"));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.deals).setText("Deals"));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.account).setText("Account"));
viewPager = v.findViewById(R.id.pager);
adapter = new AdapterPager(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
adapter.getRegisteredFragment(viewPager.getCurrentItem());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
viewPager.setAllowedSwipeDirection(SwipeDirection.none);
// setupTabIcons();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
#Override
public void onTabSelected(TabLayout.Tab tabSelected)
{
viewPager.setCurrentItem(tabSelected.getPosition());
if(UserAccountFragment.LOG_OUT_FLAG || UserAccountFragment.LOG_IN_FLAG){
tabIconColor_Selected = ContextCompat.getColor(getContext(), R.color.colorDeal);
tabSelected.getIcon().setColorFilter(tabIconColor_Selected, PorterDuff.Mode.SRC_IN);
UserAccountFragment.LOG_OUT_FLAG=false;
UserAccountFragment.LOG_IN_FLAG=false;
}
tabIconColor_Selected = ContextCompat.getColor(getContext(), R.color.colorRed);
tabSelected.getIcon().setColorFilter(tabIconColor_Selected, PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabUnselected(TabLayout.Tab tabSelected){
viewPager.setCurrentItem(tabSelected.getPosition());
tabIconColor_DeSelected = ContextCompat.getColor(getContext(), R.color.colorDeal);
tabSelected.getIcon().setColorFilter(tabIconColor_DeSelected, PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tabSelected){
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
Adapter
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
int mNumOfTabs;
public AdapterPager(FragmentManager fragmentManager, int tabCount) {
super(fragmentManager);
this.mNumOfTabs=tabCount;
}
#Override
public Fragment getItem(int position) {
Fragment fm=null;
switch (position) {
case 0:
fm = new RestaurantsFragment();
break;
case 1:
fm = new OrdersFragment();
break;
case 2:
fm = new DealsFragment();
break;
case 3:
fm = new UserAccountFragment();
break;
}
return fm;
}
#Override
public int getCount() {
return mNumOfTabs;
}
/* #Override
public Parcelable saveState() {
// Do Nothing
return saveState();
}*/
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
Your views and solution will be appreciated. Thanks in advance

refresh adapter in fragment when it is visible

I have two fragments.. I want to refresh my listview adapter adapter.notifyDataSetChanged() in setUserVisibleHint method inside my first Fragment:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
adapter.notifyDataSetChanged();
}
}
But I get this Exception:
java.lang.NullPointerException
at com.androidbelieve.drawerwithswipetabs.FirstFragment.setUserVisibleHint(FirstFragment.java:247)
at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1175)
I'm sorry I know a little about Fragments, what is this "setPrimaryItem" !?
This is my Tab Fragment :
public class TabFragment extends Fragment {
View x;
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(2);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
viewPager.getCurrentItem();
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new FirstFragment();
case 1 : return new ZZZFavorites();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Online";
case 1 :
return "Favorites";
}
return null;
}
}
}
Your adapter is null. Perform null-check before accessing it.
if (isVisibleToUser && adapter != null) {
adapter.notifyDataSetChanged();
}

Changing ImageView depends on Tab

I am having 2 Tab fragment in an activity.An activity has a circle imageview at the center. While I swipe 1st Fragment,I need to show 1st image & same as for 2nd tab swipe with different image.
UPDATE:
static class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
Bundle bundle = new Bundle();
bundle.putInt("position", position);
switch (position) {
case 0:
imgProfile.setImageResource(R.drawable.login_logo);
return new LogInFragment();
case 1:
imgProfile.setImageResource(R.drawable.add_image);
return new SignUpFragment();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "LOGIN";
case 1:
return "SIGNUP";
}
return null;
}
}
ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (i == 0) {
ImageView.setBackgroundResource(R.drawable.image1);
}
else if (i ==1) {
ImageView.setBackgroundResource(R.drawable.image2);
}
}
});
Ok now I understand what you want to do:
First delete all the code where you change the image and try this:
static class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
Bundle bundle = new Bundle();
switch (position) {
case 0:
yourImageView.setImageResource(R.id.yourResource1);
fragment = new LogInFragment();
break;
case 1:
yourImageView.setImageResource(R.id.yourResource2);
fragment = new SignUpFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
String str = "";
switch (position) {
case 0:
str = "LOGIN";
break;
case 1:
str = "SIGNUP";
break;
}
return str;
}
}
Thats all you need
Finally Got it by using the following code by made some modification in #sasikumar answer.
Instead of put onPageScrollStateChanged I used to get position in onPageSelected
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
int i = 0;
if (position == 0) {
Log.e("Tab Position", String.valueOf(position));
imgProfile.setImageResource(R.drawable.login_logo);
} else if (position == 1) {
Log.e("Tab Position", String.valueOf(position));
imgProfile.setImageResource(R.drawable.add_image);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

Fragment Pager Adapter and Pager View loading next fragment in background

i am using Fragment Pager Adapter and PagerView to create swipe tab.
But facing some problem.
Here is my:-ViewPagerAdapter
Its showing first fragment and also showing second fragment dialog
box(loading data in background). When i swipe to second
fragment it loads third fragment dialogbox and load data in background.
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context _context;
public ViewPagerAdapter(Context context, FragmentManager fm) {
super(fm);
_context = context;
}
#Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
switch (position) {
case 0:
f = ReservationTab.newInstance(_context);
break;
case 1:
f = GalleryTab.newInstance(_context);
break;
case 2:
f = VideoTab.newInstance(_context);
break;
}
return f;
}
#Override
public int getCount() {
return 3;
}
}
And accessing from here:--
private void setUpView() {
_mViewPager = (ViewPager) findViewById(R.id.viewPager);
_adapter = new ViewPagerAdapter(getApplicationContext(),
getSupportFragmentManager());
_mViewPager.setAdapter(_adapter);
_mViewPager.setCurrentItem(0);
}
private void setTab() {
_mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
System.out.println("PRINT position-- " + position);
switch (position) {
case 0:
first_tab.setVisibility(View.VISIBLE);
second_tab.setVisibility(View.INVISIBLE);
third_tab.setVisibility(View.INVISIBLE);
break;
case 1:
first_tab.setVisibility(View.INVISIBLE);
second_tab.setVisibility(View.VISIBLE);
third_tab.setVisibility(View.INVISIBLE);
break;
case 2:
first_tab.setVisibility(View.INVISIBLE);
second_tab.setVisibility(View.INVISIBLE);
third_tab.setVisibility(View.VISIBLE);
break;
}
}
});
}
#Override
public void onTabChanged(String arg0) {
// TODO Auto-generated method stub
}
This is the intended behaviour.
If you don't want ViewPager to load next fragment in background you should invoke setOffscreenPageLimit(0).
See also http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit%28int%29

Categories

Resources