我有一个Activity
( MainActivity
) ,其中包含一个Fragment
( PlaceholderFragment
) 和一个TextView
( myTextView
) 。我尝试通过下面TextView
的代码更改文本,MainActivity
但始终myTextView
是null
。
我的 MainActivity
班级:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
PlaceholderFragment myPlace = mSectionsPagerAdapter.getPlaceholde(1);
myPlace.setText("New Text");
return true;
}
return super.onOptionsItemSelected(item);
}
我的 SectionsPagerAdapter
班级:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return 4;
}
public PlaceholderFragment getPlaceholde(int position) {
return PlaceholderFragment.newInstance(position);
}
}
我的 PlaceholderFragment
班级:
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
TextView myTextView;
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
public void setText(String s){
if(myTextView!=null) {
myTextView.setText(s);
}else{
Log.w("myTextView","NULL"); // problem is here: that this line is always launched
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
myTextView = (TextView)rootView.findViewById(R.id.section_label);
myTextView.setText("some text");//work well
return rootView;
}
}
}