2012-10-04 32 views
0

我有一个布局文件,其中包含一个listview,我想填充一个片段的帮助。但它继续给我错误。 布局文件:从片段填充listview

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" > 

<ListView 
    android:id="@+id/list" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" > 
</ListView> 

<TableLayout 
    android:id="@+id/details" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:stretchColumns="1" > 

    <Button 
     android:id="@+id/create_patient_button" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/create_patient_button" /> 
</TableLayout> 

</RelativeLayout> 

我fragmentActivity:

public class BasicFragmentActivity extends FragmentActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 


    setContentView(R.layout.create_patient_view); 

    FragmentManager fm  = getSupportFragmentManager(); 
    Fragment  fragment = fm.findFragmentById(R.id.list); 

    if (fragment == null) { 


     FragmentTransaction ft = fm.beginTransaction(); 
     ft.add(R.id.list, new BasicFragment()); 
     ft.commit(); // Make sure you call commit or your Fragment will not be added. 
        // This is very common mistake when working with Fragments! 
    } 
} 

} 

我ListFragment:

public class BasicFragment extends ListFragment { 

private PatientAdapter pAdapter; 

@Override 
public void onActivityCreated(Bundle savedState) { 
    super.onActivityCreated(savedState); 

    pAdapter = new PatientAdapter(getActivity(), GFRApplication.dPatients); 
    setListAdapter(pAdapter); 
} 
} 

错误: java.lang.UnsupportedOperationException:addView(查看)不支持AdapterView

回答

0

findFragmentById(...) fu nction以片段(!)的ID作为参数。但你用R.id.list这是ListView的ID<ListView android:id="@+id/list" ...)。这是错误的,因为ListView不是片段。这是第一个问题。

第二个问题是:

FragmentTransaction ft = fm.beginTransaction(); 
     ft.add(R.id.list, new BasicFragment()); 

ft.add()函数第一个参数是要在其中把你的片段容器的ID。但是您使用R.id.list这是您的ListView的ID。这是错误的,因为ListView不是您可以直接放置片段的容器。

如果你想要把碎片进入ListView项目,您可以:

  1. 填补ListView与自定义视图。
  2. <fragment ...>声明为自定义视图布局(XML)。或者在自定义视图布局(例如FrameLayout)中创建片段容器,并在运行时放置片段(在getView()方法中)。
+0

我已经试过这种方式,但不知何故,当我尝试它,这次它的工作。感谢指针:) – Bohsen