Access TextView in ViewPager from Activity

I have an Activity with a ViewPager containing several fragments. how can I now access the TextView in one of these fragments to change its text from the main action? I tried several methods, and they all ended with a NullPointerException exception.

Activity:

public class SummonerOverview extends SherlockFragmentActivity implements TabListener, OnPageChangeListener { private ViewPager mPager; private PagerAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.summoner_overview); initialize(); } private void initialize() { // initialize Pager mPager = (ViewPager) findViewById(R.id.viewpager); mAdapter = new PagerAdapter(getSupportFragmentManager()); mPager.setAdapter(mAdapter); mPager.setCurrentItem(1); mPager.setOnPageChangeListener(this); } } 

Pageradapter:

 public class PagerAdapter extends FragmentPagerAdapter { public PagerAdapter(FragmentManager fm) { super(fm); frags = new Fragment[3]; frags[0] = new StatisticsFragment(0); frags[1] = new RatingsFragment(1); frags[2] = new HistoryFragment(2); } private final int NUM_PAGES = 3; Fragment[] frags; @Override public Fragment getItem(int arg0) { if (arg0 == 0) return frags[0]; else if (arg0 == 1) return frags[1]; else return frags[2]; } @Override public int getCount() { return NUM_PAGES; } } 

Fragment:

 public class StatisticsFragment extends SherlockFragment { public StatisticsFragment(int fragNr) { this.fragNr = fragNr; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_overview_statistics, container, false); return v; } } 

The text image in Statistical Snippet is marked with id in fragment_overview_statistics.xml, but when I try

 TextView tv = (TextView) findViewById(R.id.id_of_the_textview) tv.setText("text"); 

from inside the onCreate () Activity method after the initialize () method, I get an exception.

+4
source share
1 answer

Well, after another hour of searching on Google, I think I will solve my own question (although I am sure there is a better way to solve this)

Now I store all the data that the fragments display in MainActivity, and allow Fragmets to use this data in their onCreateView() method using the public Activity methods.

In the PagerAdapter, I rewrote getItemPosition ():

 public int getItemPosition(Object object) { return POSITION_NONE; } 

Now, every time I update some data, I also call mAdapter.notifyDataSetChanged() , which causes all fragments to be recreated.

It works, although it looks bad to me. I am sure that there should be a better solution, because now I need to recreate all the fragments to change one TextView of one fragment, which, of course, is not the way it should be done.

0
source

All Articles