问题描述
当我打电话findFragmentById()与我的片段的ID,它返回null。让我告诉你的code。
When i call findFragmentById() with the id of my fragment, it return null. Let me show you the code.
的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);
我得到空,但是当我打电话 fm.findFragmentById (R.id.main_fragment);
我得到的片段
The thing is that when i call fm.findFragmentById(R.id.login_fragment);
I get null but when I call fm.findFragmentById(R.id.main_fragment);
I get the fragment.
推荐答案
刚刚发现我的错误。
在我MainActivity.java我是进口 android.support.v4.app.Fragment;
在我LoginFragment.java我是进口安卓.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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!