5

I want to passes some value inside button click with viewpager tab fragment changing. I have two question.

  1. what is the best way to passes data?
  2. If I use static data what will be problem? such like:

    public static string abc=""
    
    case R.id.IVActionMore:   
    ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.tabs_viewpager);
    viewPager.setCurrentItem(3);
    //abc = "action";
    break;
    
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
t.gakk
  • 77
  • 2
  • 10
  • 1
    have you tried **addOnPageChangeListener** – Amit Vaghela Sep 06 '17 at 06:14
  • Well for me there is no problem in using static string, I also use it to pass some info around – Pulkit Sep 06 '17 at 06:15
  • 1
    I only dabbled in Android development, but there were Context objects you should use to put data. A static is not a great idea because they aren't controlled by the lifecycle concept, so your App may be reloaded without noticing and the data is gone. – daniu Sep 06 '17 at 06:19
  • yes I also tried only for tab change but how can I passes data. and what will be the best way. – t.gakk Sep 06 '17 at 06:22

2 Answers2

1
  1. Use addOnPageChangeListener

void addOnPageChangeListener (ViewPager.OnPageChangeListener listener) Add a listener that will be invoked whenever the page changes or is incrementally scrolled.

How ?

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

    }

    @Override
    public void onPageSelected(int position) 
    {

     if(position == 3)
     {
           // DO your work
     }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

OnClick

 buttonOBJ.setOnClickListener(new OnClickListener()
   {
             @Override
             public void onClick(View v)
             {
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
             } 
   }); 
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

You can use shared-preference to set and get the data. using static is not a great idea. check the link

https://stackoverflow.com/a/23024962/4549220

Md Tariqul Islam
  • 2,736
  • 1
  • 20
  • 35
  • Is it best way to passes data ? – t.gakk Sep 06 '17 at 07:28
  • 1
    You can check this: https://stackoverflow.com/questions/4878159/whats-the-best-way-to-share-data-between-activities https://stackoverflow.com/questions/7885276/how-to-share-same-data-between-multiple-activities-in-android – Md Tariqul Islam Sep 06 '17 at 09:46