My Fragment课程:
onCreatedView:
parentActivity = (MainActivity) getActivity();
parentView = inflater.inflate(R.layout.fragmentla, container, false);
mFragmentAdapter = new myFragmentAdapter(parentActivity.getSupportFragmentManager(), parentView.getContext());
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) parentView.findViewById(R.id.viewpager);
viewPager.setAdapter(mFragmentAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) parentView.findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
这是我的片段(蓝色边框)。我的片段包含工具栏,tablayout和viewpager。
My FragmentAdapter类:
public class myFragmentAdapter extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "ITEM1", "ITEM2" };
private Context context;
public myFragmentAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
@Override
public int getCount() {
return 2;
}
@Override
public Fragment getItem(int position) {
if(position == 0) {
return FirstFragment.newInstance(position + 1);
} else {
return SecondFragment.newInstance(position + 1);
}
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
这是我的FirstFragment类:
public static FirstFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
FirstFragment fragment = new FirstFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parentView = inflater.inflate(R.layout.fragment_first_newest, container, false);
sometext = (TextView) parentView.findViewById(R.id.wi_my_text);
return parentView;
}
所以,我的问题是:每当我按下工具栏中的菜单按钮时,textview应该改变,但是这个返回null导致“onCreatedView”不再被调用。我在Fragment类中试过这个:
public boolean onOptionsItemSelected(MenuItem item){
...
Fragment mFragment = mFragmentAdapter.getItem(0);
if(mFragment instanceof FirstFragment){
((FirstFragment) mFragment).OnButtonPressed();
}
}
然后在我的FirstFragment上,但仍然得到null异常:
public void OnButtonPressed() {
someText.setText("its working");
createLocationRequest();
}
更新:我的XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:id="@+id/wi_my_text"
android:layout_height="24dp"
android:layout_gravity="center"
android:gravity="center"
android:textStyle="bold"
android:paddingEnd="5dp"
android:text="texttest"/>
</LinearLayout>