我正在开发一个基于 viewPager 的简单应用程序。我正在尝试更改 mainActivity 片段内 textView 中的文本。我试图在 init() 方法(片段被实例化的地方)之后立即调用 textV.setText(String),但是 OnCreateView 执行得更晚,所以在那一刻对 textV 的引用为空。textV的textView放在tab0layout.xml中,布局文件膨胀时变成!=null,在Fragment0的OnCreateView方法内部引用。如何在 MainActivity 中获得对 textV 的有效引用?在 OnCreateView 中设置文本工作正常,但我需要它在 mainActivity 中可用。
这是整个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;
}
}
}