Cannot Change TextView Value Inside Fragment From FragmentActivity
I'm developing a simple app based on viewPager. I'm trying to change the
text in a textView inside a fragment from the mainActivity. I tried to
call textV.setText(String) right after the init() method(where the
fragment is instantiated), but the OnCreateView is executed much later, so
the reference to textV is null in that moment. The textV textView is
placed in tab0layout.xml, and become != null when the layout file is
inflated, and it is referenced inside OnCreateView method of Fragment0.
How can I get a valid reference of textV inside my MainActivity? Setting
the text from within the OnCreateView works fine, but I need it available
in the mainActivity.
Here is the whole java file:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();//fragment is instantiated
Fragment0.textV.setText("new text");//doesn't work, now textV is null!!
}
private void init() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment0.class.getName()));
this.mSectionsPagerAdapter = new
SectionsPagerAdapter(super.getSupportFragmentManager(), fragments);
mViewPager = (ViewPager)super.findViewById(R.id.pager);
mViewPager.setAdapter(this.mSectionsPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction
fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction
fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction
fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment>
fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
/* (non-Javadoc)
* @see android.support.v4.view.PagerAdapter#getCount()
*/
@Override
public int getCount() {
return this.fragments.size();
}
}
public static class Fragment0 extends Fragment {
static TextView textV;
public Fragment0() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab0_layout, container,
false);
textV = (TextView)rootView.findViewById(R.id.text);
return rootView;
}
}
}
}
No comments:
Post a Comment