简体   繁体   中英

why does findFragmentById always returns null

I am attempting get my fragment using findFragmentById but every time I get null in its place, I have also tried using findFragmentByTag and adding a tag to my add transaction, but that also does the same.

The following code is a modified blank starting template (for simplicity's sake)

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    setContentView(R.layout.activity_main);

    FragmentManager fragmentManager = getFragmentManager();

    if (savedInstanceState == null) {
        fragmentManager.beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    PlaceholderFragment placeholderFragment = (PlaceholderFragment) fragmentManager
            .findFragmentById(R.id.container);

    if (placeholderFragment == null) {
        Log.i("TAG", "placeholderFragment is null");
    } else {
        Log.i("TAG", "placeholderFragment is not null");
    }
}

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        return rootView;
    }
}

}

I have tried replacing the add with add(R.id.container, new PlaceholderFragment(), "TAG") then attempt to access it with findFragmentByTag("TAG") also to no success.

how can I get my code to work as intended?

I think the problem is that you are trying to find it immediately after you add the Fragment . In that little time the Fragment is probably not added yet.

What you can you is that you already have the fragment while you are adding it.

findFragmentById() function is generally for accessing Fragments in other functions after you already added them for a while.

Here is an example

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
    setContentView(R.layout.activity_main);

    FragmentManager fragmentManager = getFragmentManager();
    PlaceholderFragment placeholderFragment = new PlaceholderFragment();

    if (savedInstanceState == null) {
        fragmentManager.beginTransaction()
                .add(R.id.container, placeholderFragment).commit();
    }
}

public void anotherFunc() {

    PlaceholderFragment placeholderFragment = (PlaceholderFragment) fragmentManager
            .findFragmentById(R.id.container);
}

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