android - 尝试将 fragment 添加到我的 fragment 容器 FrameLayout

标签 android android-layout android-fragments android-framelayout

我创建了一个名为 editor.xml 的 xml 文件,其中包含一个 FrameLayout。在我的主要 Activity 中,我试图将我的自定义 fragment 添加到我的 FrameLayout。

尝试添加 fragment 时收到的错误是:

FragmentTransaction 类型中的方法 add(int, Fragment) 不适用于参数 (int, editorFrag)

但是我的 editorFrag 扩展了 Fragment 所以我对为什么会发生这种情况感到困惑。下面是我提到的文件的代码。任何帮助表示赞赏。

Editor.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />

editorFrag.java

public class editorFrag extends Fragment
{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) 
    {

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.newlevel, container, false);
    }
}

MainActivity.java

public class editorActivity extends FragmentActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.editor);

        // Check that the activity is using the layout version with the fragment_container FrameLayout
        if(findViewById(R.id.fragment_container) != null)
        {
            // if we are being restored from a previous state, then we dont need to do anything and should
            // return or else we could end up with overlapping fragments.
            if(savedInstanceState != null)
                return;

            // Create an instance of editorFrag
            editorFrag firstFrag = new editorFrag();

            // add fragment to the fragment container layout
            getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, firstFrag);
        }
    } 
}

回答:

Luksprog 在下面通过告诉我检查我的进口来为我回答了这个问题。 Eclipse 选择导入 Fragment 的 SDK 版本,而不是我需要的支持版本。谢谢你的帮助。

最佳答案

您忘记commit()您的交易。

关于android - 尝试将 fragment 添加到我的 fragment 容器 FrameLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12114015/

相关文章:

android - 下拉菜单的自定义 UI

android - android 中的 TileMap

java - GridLayout 中的按钮对齐方式

android - CardView 角在 AlertDialog 中不圆

Android Studio 无法生成签名的 apk

java - 无法将文档插入 mongodb 数据库会出现 NetworkOnMainthread 异常

android - 单击父 LinearLayout 时如何获取子 TextView 的值?

java - 替换 fragment 时出错

android - 方向更改后未重新添加 fragment

android - 如何将字体设置为 fragment 中的 TextView ?