如何将android.support.v4.app.ListFragment加到activity?

How to add android.support.v4.app.ListFragment to activity?

我有 MainActivity 布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <FrameLayout
        android:id="@+id/fragment2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
    </FrameLayout>
</LinearLayout>

MainActivity.onCreate() 方法中我尝试添加一个 ListFragment:

MyFragment themesFragment = new MyFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.fragment2, themesFragment);
        ft.commit();

但随后出现以下错误:

Error:(19, 11) error: no suitable method found for add(int,MyFragment)
method FragmentTransaction.add(Fragment,String) is not applicable
(argument mismatch; int cannot be converted to Fragment)
method FragmentTransaction.add(int,Fragment) is not applicable
(argument mismatch; MyFragment cannot be converted to Fragment)

如果我使用 android.app.ListFragment 添加成功,但我有问题 CursorLoader

将数据从数据库加载到片段中,同时通过单击按钮从 activity 添加和删除数据的最佳方式是什么?

如果使用android.support.v4.ListFragment,则必须使用getSupportFragmentManager()而不是getFragmentManager()

您的 activity 必须扩展 FragmentActivity