我正在開發基於viewPager的簡單應用程序。 我想從mainActivity中改變片段內的textView中的文本。 我試圖在init()方法(其中實例化片段)後立即調用textV.setText(String),但OnCreateView稍後執行,因此對textV的引用在那一刻爲null。 textV textView放置在tab0layout.xml中,當佈局文件膨脹時變爲!= null,並在Fragment0的OnCreateView方法內引用它。我如何在MainActivity中獲得textV的有效引用?設置從OnCreateView內的文本工作正常,但我需要它在mainActivity中可用。無法從片段活動更改片段內的TextView值
這裏是整個Java文件:
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;
}
}
}