简体   繁体   中英

Fragment view property is null when called later

I have a FirstFragment with viewPager (ViewPager contains several TestFragments). FirstFragment also contains a button. I would like to change UI of current TestFragment when I click the button.

Unfortunately when I call getView() or try to access the stored property (View rootView). They both return null.

How should I approach this?

class FirstFragment extends Fragment{
    private ViewPager mViewPager;
    private TestAdapter testAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.first_layout, container, false);
        testAdapter = new TestAdapter(getFragmentManager());
        mViewPager = (ViewPager) view.findViewById(R.id.pager);
        mViewPager.setAdapter(testAdapter);

        mViewPager.setAdapter(questionPagerAdapter);
        view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((TestFragment)testAdapter.getItem(mViewPager.getCurrentItem())).doSomethingOnFragmentUI();
            }
        });
        return view;
    }
}


class TestFragment extends Fragment{
    private View rootView;
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.my_layout, container, false);
        return rootView;
    }
    public void doSomethingOnFragmentUI(){
        if(rootView != null){
            //rootView is always null at this point
        }
    }
}

Please note that viewPager creates a new fragment everyting .getItem() is called. I do not cache the fragments. This problem occured when I stopped "caching" the fragments in HashMap (FirstFragment was keeping the reference).

Just so you can have a resolved question:

  1. You need to call getChildFragmentManager() when working with Fragments inside Fragments.
  2. Never invoke getItem() inside a PagerAdapter, unless you precisely know what you're doing. It's meant to be called by the system, not by you. If you really want to invoke your Fragments in your Pager from outside, you can use this approach: https://stackoverflow.com/a/15261142/535762

Hope that covers all. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM