如何将android.support.v4.app.ListFragment添加到活动?

时间:2015-04-17 13:05:51

标签: android android-fragments android-listfragment android-cursorloader

我有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有疑问。

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

1 个答案:

答案 0 :(得分:0)

如果您使用android.support.v4.ListFragment,则必须使用getSupportFragmentManager()代替getFragmentManager()

您的活动必须延伸FragmentActivity