findFragmentById返回null

Kar*_*r0t 31 android nullpointerexception android-fragments

当我用我的片段的id调用findFragmentById()时,它返回null.让我告诉你代码.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

        <fragment android:name="com.madduck.test.app.fragment.MainFragment"
                  android:id="@+id/main_fragment"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent" />

        <fragment android:name="com.madduck.test.app.fragment.LoginFragment"
                  android:id="@+id/login_fragment"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

MainActivity.java

private static final int LOGIN = 0;
private static final int MAIN = 1;
private static final int FRAGMENT_COUNT = MAIN +1;
private Fragment[] fragments = new Fragment[FRAGMENT_COUNT]

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

    FragmentManager fm = getSupportFragmentManager();
    fragments[LOGIN] = fm.findFragmentById(R.id.login_fragment);
    fragments[MAIN] = fm.findFragmentById(R.id.main_fragment);

    FragmentTransaction transaction = fm.beginTransaction();
    for (Fragment f : fragments) {
        if (f != null)
            transaction.hide(f);
        else
            Log.e(TAG, "???");
    }

    transaction.commit();
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我打电话给fm.findFragmentById(R.id.login_fragment);我时,我会得到null但是当我打电话时fm.findFragmentById(R.id.main_fragment);我得到片段.

cod*_*aps 86

答案Kar0t非常好,但这可能对某人有所帮助.在我的情况下,我在片段内部有一个片段,我得到了错误的FragmentManager.我只需要打电话:

getChildFragmentManager()

然后像往常一样找到片段:

fm.findFragmentById(R.id.fragment)
Run Code Online (Sandbox Code Playgroud)

  • 我也在这里挣扎.非常感谢! (6认同)

Kar*_*r0t 34

刚发现我的错误.

在我的MainActivity.java中,我正在导入android.support.v4.app.Fragment;并在我导入的LoginFragment.java中android.app.Fragment;.我把它改成了同样的东西,然后fm.findFragmentById(R.id.login_fragment)返回正确的片段.

  • 感谢您的见解.在我的情况下,使用getSupportFragmentManager()而不是getFragmentManager()解决了问题,因为我的底层片段来自支持包. (2认同)

Pav*_*ley 7

与具体问题无关,但与接收null有关findFragmentById,如果您findFragmentById在提交后立即调用,它将返回 null 或最后一个片段(提交前),原因是提交执行异步请求。

从文档:

安排此事务的提交。提交不会立即发生;它将被安排为主线程上的工作,以便在该线程准备好时完成。

如果您需要findFragmentById立即,例如更改状态栏文字颜色添加片段,通话后executePendingTransactions()commit()

getSupportFragmentManager().executePendingTransactions();
//call findFragmentById 
Run Code Online (Sandbox Code Playgroud)