我從來沒有使用Fragments,但現在我有一個PlayerStatus片段,我想在兩個不同的活動中使用它。它顯示播放器狀態:getFragmentById返回null
public class PlayerStatus extends Fragment {
Player player;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.player_status, container, false);
return view;
}
public void setPlayer(Player player) {
this.player = player;
}
}
碎片的佈局是這樣的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:paddingTop="0dp" >
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
layout="@layout/money" />
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
layout="@layout/wins" />
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
layout="@layout/level" />
</LinearLayout>
我得到它的活動是這樣的:
@Override
protected void onResume() {
super.onResume();
setContentView(R.layout.game);
fPlayerStatus = (PlayerStatus) getFragmentManager().findFragmentById(R.id.fPlayerStatus);
fPlayerStatus總是返回null 。 我在做什麼錯?
謝謝!它幫助 - 現在我有IllegalArgumentException,而不是NPE :)我已經多次閱讀這些文章,我想通過xml layout =>靜態添加片段(如developer.android.com/guide/components/fragments.html中所述)添加)「當系統創建這個活動佈局時,它會實例化佈局中指定的每個片段併爲每個片段調用onCreateView()方法來檢索每個片段的佈局。系統直接插入片段返回的View來代替元素「。 –
所以我認爲我不必使用fragmentTransactions(和framelayout)。但現在 - 使用fragmentTransactions - 我應該使用frameLayout,是嗎? –
您的意思是您的XML文件中定義碎片的主佈局。不管你是否可以使用任何佈局 – Khay