Why fragment created in FragmentPagerAdapter is skipped sometimes when using getactivity() to find view?

75 views Asked by At

I am using FragmentPagerAdapter to create multiple instances of fragment A.

I tried 2 ways of finding views inside fragement A:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v= inflater.inflate(R.layout.fragment_cat_table, container, false);
    title = (TextView) v.findViewById(R.id.cat_title);
    pagenum = (TextView) v.findViewById(R.id.page_number);
    title.setText(catName);
    pagenum.setText("page #"+String.valueOf(catIndex));
    return v;
}

The above code works fine, the view is from inflater. But the second way:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    title = (TextView) getActivity().findViewById(R.id.cat_title);
    pagenum = (TextView) getActivity().findViewById(R.id.page_number);
    title.setText(catName);
    pagenum.setText("page #"+String.valueOf(catIndex));
}

In this way I use getactivity() to find view. Weird thing happens: if I have 2 pages with 2 instances of fragment A: fragment A_0, fragment A_1, then fragement A_0 will not shown up, fragment A_1 will be shown in page 0 . Page 1 will contain a raw fragment A: all textview(title and pagenum) in the fragment are not set

I am curious about why this is happening.

1

There are 1 answers

0
yidiyidawu On BEST ANSWER

After thinking about it a bit...I figured out. pageadapter will create the fragment in advance such that onActivityCreated will be called before the fragment is on the screen. So if I do findviewbyId() in onActivityCreated, it is possible that it will find the view in other page/fragment which is currently being displayed and modify it