user3227070 user3227070 - 1 year ago 94
Android Question

Set fragment as layout on activity start

public class MainActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null) {
.add(, new homePage())

Here is the error which I got:

Cannot resolve method add(int, etc...) on line add(, new

So basically i created three fragments and one activity. My activity does not have a lay-out (though it does obviously have a layout page, it's ID is container). I want to add the homePage layout file to the container when the activity starts, but this doesn't seem to be working. I've only created the layout etc so far, and now I'm trying to add the java code but I'm unsure why this isn't working.

I haven't edited the java code of any of the fragments yet so it's basically the code android studio adds to it on creation.

public class homePage extends Fragment {

private OnFragmentInteractionListener mListener;
private View view;

public homePage() {
// Required empty public constructor

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home_page, container, false);
Button btnLogin = (Button) view.findViewById(;
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
return view;

public static homePage newInstance() {
homePage fragment = new homePage();
Bundle args = new Bundle();
return fragment;

public void loginView(){}

public void onAttach(Context context) {
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");

public void onDetach() {
mListener = null;

* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* ""
* >Communicating with Other Fragments</a> for more information.
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);

Answer Source

This might be because your homeFragment extends the Fragment from the support library ( and hence your MainActivity should use getSupportFragmentManager() instead of getFragmentManager() which is a part of