的activity_fragment.xml代碼:FragmentManager findFragmentById返回NULL
<?xml version="1.0" encoding="utf-8" ?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
CrimeListActivity.java
package com.sinory.criminalintent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
public class CrimeListActivity extends SingleFragmentActivity {
@Override
protected Fragment createFragment() {
return new CrimeListFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("CrimeListActivity", "create");
}
}
SingleFragmentActivity.java
的代碼package com.sinory.criminalintent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public abstract class SingleFragmentActivity extends FragmentActivity {
protected abstract Fragment createFragment();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (null == fragment) {
fragment = new CrimeListFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
}
剛開始的代碼學習Android。爲什麼片段fragment = fm.findFragmentById(R.id.fragmentContainer)爲空?請幫幫我。
「您只能在xml文件中定義片段時使用此方法。」這不完全正確。您可以將fragment添加到activity.xml中的指定ViewGroup中:getFragmentManager() .beginTransaction() .add(R.id.someFrameLayoutForExample,new MainFragment()) .commit();然後檢索它getFragmentManager()。findFragmentById(R.id.someFrameLayoutForExample);這裏的關鍵點和使用findFragmentByTag()是在找到之前必須先添加。不管它將如何完成 - 通過xml或代碼。 – Deepscorn