0

尝试在 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。为什么它在我的布局中找不到片段?

4

3 回答 3

1

The problem that you have is that you declared in the xml the Fragment as a ListFragment.

getSupportFragmentManager().findFragmentById(android.R.id.content) uses Support fragment manager, so you will need a SupportMapFragment

Try this:

<fragment 
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:id="@android:id/content"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>
于 2014-01-13T11:55:15.630 回答
0

不应该

android:id="@android:id/content"

android:id="@+id/content"

?

文档看来,您似乎使用了错误的语法。

我也不确定你的链式方法是否能像所写的那样正常工作。改变

 getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(android.R.id.content, list);
transaction.commit();

即使那样,老实说,我也不知道你会在那里做什么。您知道FragmentTransaction 的 add 方法在您使用它时正在尝试将片段添加到容器中,在您的 if 中,该容器已经被确定为具有空值?

于 2013-06-27T23:09:48.140 回答
0

mListFragment在类覆盖中尝试这个onCreate()并调用setRetainInstance(true);

public static class mListFragment extends SherlockListFragment {

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setListAdapter(adapter);
    setListShown(true);
}

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
  }

}

于 2020-01-20T17:31:36.707 回答