简体   繁体   中英

Why can't I instantiate this Fragment on Android?

Here is the code I have. I'm getting a red line under new MainFragment(); with the error Type mismatch: cannot convert from WishlistFragment to Fragment :

Fragment newfragment = new MainFragment();   

Here is what my MainFragment.java file looks like:

public class MainFragment extends Fragment {
    public MainFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment_main, container, false);
    }
}

Any ides on why this is happening? I have a feeling it's something stupid I am looking over and I am just code-blind right now from a long day.

Make sure that both places are importing the same Fragment class. It feels a bit like in one place you are importing android.app.Fragment (the native API Level 11 version of fragments) and in the other places you are importing android.support.v4.app.Fragment (the fragments from the Android Support package).

Figured out the issue.... my MainActivity.java file was using:

import android.support.v4.app.Fragment;

and my MainFragment.java file was using:

import android.app.Fragment;

So there was a mismatch. I am using ICS 4.0 and higher as my lowest API version. Changing everything to import to the v4 API solved my issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM