0

I have an activity that cointains a FragmentPagerAdapter with its view. After the view is created I need to run this method to change textviews (defined in the FragmentPagerAdapter):

        public void onPageSelectedCustom(int position) {
        int ValidView;
        FragmentManager myFrag = passedAct.getSupportFragmentManager();
        String name = makeFragmentName(mViewPager.getId(), position);
        ArrayListFragment f = (ArrayListFragment) myFrag.findFragmentByTag(name);
        if(f!=null) {
            ValidView= 1;
            View fragView = f.getView();
            View tv = fragView.findViewById(R.id.text);
            ((TextView)tv).setText("VALID FRAGMENT #" + position);
            Log.d("Fragment", "fragment is valid: " + position);
        } else {
            ValidView= 0;
            Log.d("Fragment", "fragment is not valid: " + position);
        }
}

I tried calling onPageSelectedCustom() in the FragmentPagerAdapter's constructor however f is always null thus never executing the code. I tried working with the activity's onCreate(), onResume() and onPostResume() but they all get called before the Fragment's views are created.

Any ideas of what went wrong?

asg2012
  • 315
  • 1
  • 6
  • 15

1 Answers1

0

Fragment follow a different lifecycle than Activity, so your approach with Activity's lifecycle methods will not work.

From your code, it seems what you want is a way to communicate with the Fragment(s) about which position it is at in the ViewPager. To achieve this you can send your data in Bundle from your Activity to your Fragment(s), and then change the Fragment's TextView accordingly from onCreateView(). See here.

Community
  • 1
  • 1
j449li
  • 103
  • 1
  • 6