findFragmentById 返回 null [英] findFragmentById return null

查看:21
本文介绍了findFragmentById 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用片段的 id 调用 findFragmentById() 时,它返回 null.

When I call findFragmentById() with the id of my fragment, it returns 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>

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();
}

问题是当我调用 fm.findFragmentById(R.id.login_fragment); 我得到一个 null 但是当我调用 fm.findFragmentById(R.id.main_fragment); 我得到了片段.

The thing is that when I call fm.findFragmentById(R.id.login_fragment); I get a null but when I call fm.findFragmentById(R.id.main_fragment); I get the fragment.

推荐答案

刚刚发现我的错误.

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

In my MainActivity.java i was importing android.support.v4.app.Fragment; and in my LoginFragment.java i was importing android.app.Fragment;. I changed it to the same thing and fm.findFragmentById(R.id.login_fragment) now return the right fragment.

这篇关于findFragmentById 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆