正在尝试将片段添加到我的片段容器FrameLayout中



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

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

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

然而,我的编辑Frag扩展了Fragment,所以我对为什么会发生这种情况感到困惑。下面是我提到的文件的代码。感谢您的帮助。

编辑器.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);
    }
}

主要活动.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()您的事务。

您还忘记调用addtoBackStack()方法,否则当您按下返回按钮时,您的应用程序将关闭。

像这个一样添加commit()

 getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, firstFrag).commit();
 1-   //Add fragment container in xml file
    
    <androidx.fragment.app.FragmentContainerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fragment_container_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    </androidx.fragment.app.FragmentContainerView>

2-  //Implementation of BackStack
        fragmentTransaction.setReorderingAllowed(true);
        fragmentTransaction.addToBackStack("name");

最新更新