简体   繁体   中英

Fragments not updating in viewpager

I am pretty new to ViewPager and adapter world in android. I have seen this issue asked many times but did not quite understand so hoping for a simplified answer :).

I have a ViewPager with 3 tabs and each tab has a fragment. By default the user first sees tab2 where he gives some imput to generate a string. this string then needs to be taken in tab3 which generates a qr code from it.

the string from tab 2 is updated to a class and tab3 takes the string from there.

My Problem is that when i move from tab2->tab3 the qr code is not generated. But when i go tab2->tab1->tab3 it is generated. I am guessing it retains my old fragment .

Below are my class codes. Could you please let me know why is this viewpager behaviour so.

my FragementActivity class:

public class ConfigExchangeMain extends FragmentActivity {

FragmentPagerAdapter adapterViewPager;
SampleFragementPagerAdapterExchange adapter;
String sent;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.config_exchange_main);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

   adapter=new SampleFragementPagerAdapterExchange(getSupportFragmentManager());

    viewPager.setAdapter(adapter);
    viewPager.setCurrentItem(1);

    // Give the TabLayout the ViewPager
    TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setupWithViewPager(viewPager);

   }
}

My Pager Adapter looks like

public class SampleFragementPagerAdapterExchange extends FragmentStatePagerAdapter {

final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"CONTACTS", "HOME", "QR+SCAN"};
private ConfigDetail context;

public SampleFragementPagerAdapterExchange(FragmentManager fm) {
    super(fm);
    //this.context = context;
}

@Override
public Fragment getItem(int position) {
    switch (position) {
        case 1:
            return new ConfigExchangeNFR();
        case 0:
            return new ConfigExchangeHome();
        case 2:
            return new ConfigExchangeQR();
        default:
            return new ConfigExchangeQR();
    }
}

@Override
public int getCount() {
    return PAGE_COUNT;
}

public CharSequence getPageTitle(int position) {
    // Generate title based on item position
    return tabTitles[position];
}

@Override
public int getItemPosition(Object object) {


    return  POSITION_NONE;


 }
}

and my fragment in tab3 that is not updating:

public class ConfigExchangeQR extends Fragment {

ImageView iQRCode ;
int iQRDimension;
Button bScan;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    FacebookSdk.sdkInitialize(getActivity().getApplicationContext());

    View view1 = inflater.inflate(R.layout.config_exchange_qr, container, false);

    iQRCode = (ImageView)view1.findViewById(R.id.qrCode);

    iQRDimension = 900;

   String FinalQRCode = KeyValueDb.getPrefFinalVCard(getActivity());
    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(FinalQRCode, null,
           contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), iQRDimension);





        try {
            Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
            iQRCode.setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }

    bScan = (Button)view1.findViewById(R.id.scan_qr);
    bScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View paramAnonymousView) {

            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            startActivityForResult(intent, 0);

        }
    });


    return view1;


}
}

In ConfigExchangeMain class:

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {           
        }

        @Override
        public void onPageSelected(int position) {

         Fragment fragment= adapter.getItem(position);

           if(fragment instanceof ConfigExchangeQR ){
            ((ConfigExchangeQR)fragment).update();
           }

        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });


     @Override
public void onDestroy() {
    super.onDestroy();
    viewPager.clearOnPageChangeListeners();
}

Add this method to your ConfigExchangeQR fragment

 public class ConfigExchangeQR extends Fragment {
      ...
   public void update(){

        String FinalQRCode = KeyValueDb.getPrefFinalVCard(getActivity());
        QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(FinalQRCode, null,
        contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), iQRDimension);


      try {

        Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
        iQRCode.setImageBitmap(bitmap);

       } catch (WriterException e) {

       }



    }
 }

When you are currently in your second tab. The first and the third tab are preloaded (because the animation is smoother). When you switch to the first tab the third tab is unloaded -> so after switching back to the third tab it is recreated and it works for you.

The 3rd tab onCreateView is called before the 2nd tab is done, thats why it is not working. Try implementing logic inside the onResume() - to make sure it is always called when the focus is back on the fragment.

Hope this helps... Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM