0

试图在xml布局中查找ListFragment总是返回null。我使用了SherlockFragmentActivity和SherlockListFragment。下面是代码:findFragmentById始终为空

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

回答

0

不应该

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

android:id="@+id/content" 

documentation看来你似乎使用错误的语法。

我也不确定你的链式方法是否能正常工作。更改

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

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

即使是这样,我真的不知道你是想在那里做。您知道FragmentTransaction's add method as you're using it正试图将一个片段添加到一个容器中,该容器在您的if中已经被建立为具有空值?

+0

这似乎没有,没有。 – DaveSav

+0

你是什么意思?从[documentation] [1]看来,你似乎使用了错误的语法。 [1]:http://developer.android.com/guide/components/fragments.html#Adding – DigCamara

+0

我将xml更改为您的建议,但遗憾的是没有任何区别 – DaveSav

1

您遇到的问题是您在xml中将碎片声明为ListFragment。 。

getSupportFragmentManager()findFragmentById(android.R.id.content)采用支持片段经理,所以你需要一个SupportMapFragment

试试这个:

<fragment 
    android:name="com.google.android.gms.maps.SupportMapFragment" 
    android:id="@android:id/content" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
/>