错误找不到合适的add方法(int,Fragment)

时间:2016-05-26 17:25:12

标签: android android-fragments error-handling exception-handling

我试图在活动中夸大片段,这是代码。

public class DetailActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_detail);
            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.container2, new DetailFragment()) 
                        .commit();    //Line with Error
            }
        }


        @Override
        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;
        }

        @Override
        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);
        }
    }

这是我的DetailFragment

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

    public DetailFragment() {
    }

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

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

这里是fragment_detail

的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:textSize="18sp"
    android:id="@+id/fragment_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</LinearLayout>

我面临的错误是cannot resolve method 'add(int,com.example...DetailFragment)'。因为,我是android的初学者,请指导我如何处理,解决此类错误。

2 个答案:

答案 0 :(得分:8)

您的DetailFragment需要从android.support.v4.app.Fragment而不是Fragment扩展。像这样的东西

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

 ......
}

答案 1 :(得分:0)

Make sure your DetailFragment uses the fragment from the version 4 support library and import the library below into your fragment class. The problem is that you are using android.app.fragment instead of android.support.v4.app.Fragment.

import android.support.v4.app.Fragment;

public class DetailFragment extends Fragment{

}