试图将片段添加到我的片段容器FrameLayout

Ped*_*rom 25 android android-layout android-fragments android-framelayout

我创建了一个名为editor.xml的xml文件,其中包含一个FrameLayout.在我的主要活动中,我正在尝试将自定义片段添加到FrameLayout中.

我在尝试添加片段时收到的错误是:

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" />
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

回答:

Luksprog通过告诉我检查我的进口来回答这个问题.Eclipse选择导入Fragment的SDK版本而不是我需要的支持版本.感谢您的帮助.

Mar*_*ski 33

你忘记了commit()你的交易.


小智 5

您也忘记调用该addtoBackStack()方法,否则当您点击后退按钮时应用程序将关闭.


Mil*_*lon 5

像这样添加commit()

 getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, firstFrag).commit();
Run Code Online (Sandbox Code Playgroud)