Skip to content Skip to sidebar Skip to footer

Viewpager With Fragments Holding Gridview

I have a ViewPager with two Fragments , each Fragment has a GridView Frag1.java public class Frag1 extends Fragment{ GridView grid; @Override public View onCreateView(LayoutInflate

Solution 1:

This is weird...

@OverridepublicvoidonActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    grid = (GridView) getActivity().findViewById(R.id.gridView1);
    grid.setAdapter(newMyAdapter());

}

Why are you looking for gridView in Activity? Probably you should do this in your onCreateView without messing in onActivityCreated

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
        ViewGrouprootView= (ViewGroup) inflater.inflate(R.layout.frag, container, false);
        grid = (GridView) rootView.findViewById(R.id.gridView1);
        grid.setAdapter(newMyAdapter());
        return rootView;
}

Some explanation:

You are calling

getActivity().findViewById(R.id.gridView1);

which is searching in Activity in your ViewPager (and as it is extended ViewGroup) in its childrens (fragment layouts). Both are calling gridView1, assuming this grid is attached only to Frag1, you are creating Frag1 with this view and setting Adapter with ch drawables. Then second fragment Frag2 is created, get from Activity GridView inflated earlier in Frag1 and still present on the screen (alive, not null) and set gmc adapter

Post a Comment for "Viewpager With Fragments Holding Gridview"