-1

I have a viewpager with a fragments slide, I need to know which one is on the screen to return some results to the correct fields. How to know what is on the screen?

Here are codes:

//Activity
public class ActivityAtendimentoTab extends AppCompatActivity{

    private ResultFragmentsCondutas resultFragmentsCondutas;

    //método para que possa ser passado os valores falados para os fragments.
    public interface ResultFragmentsCondutas {
        void showCondutaResults(ArrayList<String> results);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_atendimento_tab);

......

        vpPager = (ViewPager) findViewById(R.id.vpPager);
        adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
        vpPager.setAdapter(adapterViewPager);
        vpPager.addOnPageChangeListener(viewPagerPageChangeListener);
..
   }
}

Below, viewpager, which is a innerclass:

    //ViewPager inner class ActivityAtendimentoTab
    public static class MyPagerAdapter extends FragmentPagerAdapter {
        private static int NUM_ITEMS = 2;

        public MyPagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        // Returns total number of pages
        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        // Returns the fragment to display for that page
        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0: // Fragment # 0 - This will show FirstFragment
                    return new FragmentAvaliacao();
                case 1: // Fragment # 0 - This will show FirstFragment different title
                    return new FragmentReceita()
                default:
                    return null;
            }
        }

        // Returns the page title for the top indicator
        @Override
        public CharSequence getPageTitle(int position) {
            return "Page " + position;
        }

    }

I need to know which of these are on the screen to return some results, from an interface. Follow the code:

@Override
public void onResults(Bundle results) {

    //inicializando as variáveis de fragments
    av = (FragmentAvaliacao) getSupportFragmentManager().findFragmentByTag(getString(R.string.tag_fragment_avaliacao));//NULL

    //pegando a lista de comandos
    ArrayList<String> matches = results
            .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

    //Verifica qual fragment está chamando a interface
    //e passa o valor da string para que seja implementada nos respectivos campos.
    try {
        if (vpPager.getCurrentItem() == 0) {//TRUE
            resultFragmentsCondutas = av;
            resultFragmentsCondutas.showCondutaResults(matches);
}

How do I initialize av (example), is always null.

Ruan_Lopes
  • 1,381
  • 13
  • 18

1 Answers1

2

If I understood correctly you need to know what fragment is visible when you swipe it.

first option:

viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {

}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

public void onPageSelected(int position) {

    // Check if this is the page you want by position

  if{position==0){
   //is FragmentAvaliacao() do something
  } else{
   //is FragmentReceita()  do something
  }

}

});

In your case int the onPageSelected(int position) you check if it's 0 meaning "FragmentAvaliacao()" or 1 to FragmentReceita()

Second option

 @Override
 public void onResults(Bundle results) {

   Fragment page = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.of_your_viewpager + ":" + viewPager.getCurrentItem());

 if (ViewPager.getCurrentItem() == 0 && page != null) {
      ((FragmentAvaliacao)page).showCondutaResults(matches);     
 } 
}
Ruan_Lopes
  • 1,381
  • 13
  • 18
  • How can I do this? 'Cause just checking the position, is true, 0 or 1. But how do I send the data to the correct fragment? vp.getCurrentItem, do the same thing. –  Jun 04 '18 at 18:06
  • Can you take a look at my updated answer? In the first option, you can keep a local reference to the fragments in the viewpager and in the onPageSelected() you could manipulate them – Ruan_Lopes Jun 04 '18 at 18:25
  • The second case, I used, but in the viewpager, I have new `FragmentAvaliacao()`, in the viewpager I have do initiate a new FragmentAvaliacao(), and I can't set the TAG. First case, doesn't work, 'cause onResults is my problem. –  Jun 04 '18 at 18:37
  • Did you replace `getString(R.string.tag_fragment_avaliacao)` by `"android:switcher:" + R.id.of_your_viewpager + ":" + viewPager.getCurrentItem() ` ? – Ruan_Lopes Jun 04 '18 at 18:42
  • Yes. Neither option will work. The fragment is instantiated in the viewpager, which is an innerclass. the correct code would be `((new FragmentAvalation ()) page) .showCondutaResults (matches);` –  Jun 04 '18 at 18:45
  • Sorry, I made a mistake while typing. I update my answer. the correct is `((FragmentAvaliacao)page).showCondutaResults(matches); ` because you will cast the current fragment to the type you want – Ruan_Lopes Jun 04 '18 at 18:47