findFragmentByTag() returns null after perform a FragmentTransaction using replace() method

前端 未结 8 1639
广开言路
广开言路 2020-11-30 04:44

My Android app consists three fragments: A, B and C. They\'re loaded in the two containers defined in the MainActivity layout.

When th

相关标签:
8条回答
  • 2020-11-30 05:12

    Be sure you are adding or replacing the fragment in the proper way

    Next statement will add the fragment but it will return null when using getFragmentManager().findFragmentByTag(tag):

    transaction.add(R.id.mainContent, fragment);

    

    This way it will work;

    transaction.add(R.id.mainContent, fragment, tag);
    
    0 讨论(0)
  • 2020-11-30 05:22

    I'll start by apologising since I'm still very new myself...

    I think the problem may be in the declaration of the fragmentTag static String not properly getting access from the class's instances, just change that line to:

    private final static String FRAGMENT_TAG = "FRAGMENTB_TAG"; // using uppercase since it's a constant
    

    Also, I would be more explicit when declaring instances, for example:

    public void buttonListener(View v){
    
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.right_container, new FragmentB(), FRAGMENT_TAG);
        ft.commit();
    
        FragmentB fragB = (FragmentB) getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
        fragB.testView();
    }
    

    I hope you get this sorted, as I seen this question posted earlier and was surprised that it hadn't got any activity yet.

    Also, here are a couple of links to the android documentation on replace:

    Android Training - Replace

    Android Reference - Replace

    0 讨论(0)
提交回复
热议问题