将片段附加到活动

时间:2016-10-17 08:19:19

标签: android android-fragments

我正在尝试使用以下代码以编程方式将Fragment附加到我的MainAvtivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    MainFragment fragment = new MainFragment();
    fragmentTransaction.add(R.id.activity_main,fragment);
    fragmentTransaction.commit();


}

它给了我一个错误:cannot resolve add method

可以找到该应用程序here

3 个答案:

答案 0 :(得分:2)

替换您的代码:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MainFragment fragment = new MainFragment();
fragmentTransaction.add(R.id.activity_main,fragment);
fragmentTransaction.commit();

由此:

Fragment fragment = new MainFragment();
getSupportFragmentManager.begintransaction.replace(R.id.container,fragment).commit;

答案 1 :(得分:0)

首先在activity_main.after

中使用framelayout

fragmentTransaction.add(R.id.framelayout_id,片段);

比工作正常

答案 2 :(得分:0)

制作类似的功能

public void openFragment(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.fragmentContainer, fragment).commit();
    }

并在你的onCreate方法中调用它

 openFragment(new yourFragment());

在您的beginTransaction()。replace方法中,您必须传递要用其替换片段的视图