当我使用 fragment 的 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>
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);
我得到了 fragment 。
最佳答案
答案Kar0t很好,但这可能会对某人有所帮助。在我的情况下,我在 fragment 中有一个 fragment ,并且我得到了错误的 FragmentManager。我只需要打电话:
getChildFragmentManager()
然后像往常一样找到 fragment :
fm.findFragmentById(R.id.fragment)
关于android - findFragmentById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23353344/