尝试在 xml 布局中查找 ListFragment 总是返回 null。我正在使用带有 SherlockListFragment 的 SherlockFragmentActivity。这是代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_custom_layout);
adapter = new My_Custom_Adapter(this, My_Object, My_Object_2);
}
// Create the list fragment and add it as the list content.
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
mListFragment list = new mListFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class mListFragment extends SherlockListFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(adapter);
setListShown(true);
}
}
这是 xml 布局的缩短版本:
<RelativeLayout
android:id="@+id/top_control_bar">
<!-- Text Views -->
</RelativeLayout>
<RelativeLayout >
<!-- Button -->
</RelativeLayout>
<LinearLayout
android:id="@+id/start_data"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@id/top_control_bar"
android:orientation="vertical" >
<fragment
android:name="android.support.v4.app.ListFragment"
android:id="@android:id/content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
findFragmentById(android.R.id.content)
总是返回 null。为什么它在我的布局中找不到片段?