以编程方式将片段添加到android中的framelayout

时间:2013-12-08 15:56:56

标签: android fragment android-framelayout

我正在尝试构建一个结合静态和动态元素的UI。为此,我将我的活动划分为片段 - 然后通过替换片段而不是在活动之间导航来完成所有应用程序导航。

在我的主要活动布局中,我使用的是FrameLayout

<FrameLayout
        android:id="@+id/mainframe"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_below="@id/topsection"
        android:layout_above="@id/lowersection" />

我有一个声明的片段:

public class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragmentlayout, container, false);
    }
}

然后,在我的主要活动(扩展FragmentActivity并使用导入android.support.v4.app.FragmentActivity)中,我试图将此片段加载到帧布局中。

MyFragment myf = new MyFragment();

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.mainframe, myf);
transaction.commit();

我已经从许多其他示例中遵循了这一点,但是我在transaction.add()命令上收到编译器错误,似乎没有其他人遇到过。

我收到的错误是:The method add(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, MyFragment)

这是为什么? MyFragment类扩展了Fragment,所以我认为这样可行。我做错了什么?

编辑:我的主要活动的导入是:

import org.joda.time.DateTime;
import android.app.FragmentTransaction;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

1 个答案:

答案 0 :(得分:31)

检查您的进口商品。使用android.support.v4.app.FragmentTransaction代替android.app.FragmentTransaction

此外,请务必使用android.support.v4.app.Fragment并致电getSupportFragmentManager()。很容易错过这个电话/进口。通过FragmentManager的提示,转到saiful103a。

相关问题