【发布时间】:2014-06-14 17:21:02
【问题描述】:
当我使用片段的 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); 时,我得到了片段。
【问题讨论】:
-
发布完整的崩溃日志和你的片段代码
-
感谢您的快速回答,我找到了解决方案(在一个片段中使用 support.v4,在另一个片段中使用普通类型)我现在无法发布解决方案,因为我没有t 有 10 名声望,但明天会回答自己。我之前搜索了一下,没有发现与此相关的内容。
-
我怀疑这可能是问题所在。无论如何你找到它。不错
标签: android android-fragments nullpointerexception