M.S.P M.S.P - 1 year ago 137
Android Question

Error No suitable method found for add(int, Fragment)

I was trying to inflate a fragment in an Activity and here is the code.

public class DetailActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null) {
.add(R.id.container2, new DetailFragment())
.commit(); //Line with Error

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, menu);
return true;

public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
return true;

return super.onOptionsItemSelected(item);

And here is my

* A placeholder fragment containing a simple view.
public class DetailFragment extends Fragment {

public DetailFragment() {

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
return rootView;

Here goes the layout for

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content" />

The error I am facing is
cannot resolve method 'add(int,com.example...DetailFragment)'
. As, I am beginner to android, please also guide me on how should I go about, tackling such type of errors.

Answer Source

Your DetailFragment need to extends from android.support.v4.app.Fragment instead of Fragment. Something like this

public class DetailFragment extends android.support.v4.app.Fragment {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download