Reputation: 2018
I'm trying to dynamically create a fragment and am getting the following error message:
Cannot resolve method 'add(int, com.brewguide.android.coffeebrewguide.RecipeFragment)
Other answers I have looked up suggested that the library import for the fragment was off, so I've added the library imports v4.app.Fragment
instead of app.Fragment
to both the Fragment and the Activity that calls the fragment and the issue hasn't gone away. Below is my code:
MenuActivity.java
package com.brewguide.android.coffeebrewguide;
import android.support.v4.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
public class MenuActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
int position;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//retrieves intent
Intent i = getIntent();
//fetches menu option that was selected.
// 0 is the default
position = i.getIntExtra("position", 0);
// get an instance of FragmentTransaction from your Activity
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//add a fragment
RecipeFragment myFragment = new RecipeFragment();
fragmentTransaction.add(R.id.myfragment, myFragment);
fragmentTransaction.commit();
switch (position){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
Toast toast = Toast.makeText(this,
"An Error has occurred.",
Toast.LENGTH_SHORT);
toast.show();
break;
}
if(getSupportActionBar()!= null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
}
RecipeFragment.java
package com.brewguide.android.coffeebrewguide;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class RecipeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_recipe_layout, container, false);
}
public RecipeFragment(){}
}
Upvotes: 0
Views: 30
Reputation: 191728
It's not just the Fragment import... You also need the Support Fragments Manager instead of these
import android.app.FragmentManager;
import android.app.FragmentTransaction;
You need getSupportFragmentManager()
instead of getFragmentManager()
when using the Support Fragments
Upvotes: 2