How to start Fragment from Activity?

纵饮孤独 提交于 2019-12-01 18:12:27

Here is how you call a fragment from inside an Activity

Fragment fr = new FirstFragment();
fr.setArguments(args);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();

Assuming you have fragment_place represents the following:

<fragment android:name="com.company.appName.fragments.FirstFragment"
        android:id="@+id/fragment_place"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

If you are getting

Wrong 2nd argument type. Found: 'android.support.v4.app.Fragment', required: 'android.app.Fragment'

this error, check the imports, you may find the below,

import android.app.FragmentManager;
import android.app.FragmentTransaction;

delete the above imports. Change getFragmentManager()to getSupportFragmentManager()

FragmentManager fragmentManager=getFragmentManager(); to
FragmentManager fragmentManager=getSupportFragmentManager();

now we can import the,

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!