简体   繁体   中英

Error:(31, 40) error: incompatible types: android.support.v4.app.Fragment cannot be converted to android.app.Fragment

I have a problem in this code and I don't know which one I should use android.support.v4.app.Fragment or android.app.Fragment;

public class MainActivity extends AppCompatActivity {

private SharedPreferences pref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getPreferences(0);
        initFragment();
    }

    private void initFragment(){
        android.support.v4.app.Fragment fragment;
        if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){
            fragment = new ProfileFragment();
        }else {
            fragment = new LoginFragment();
        }
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_frame,fragment);
        ft.commit();
    }

}

Do not mismatch android.support.v4.app.Fragment with android.app.Fragment , use anyone of them in the whole app.

private void initFragment(){
    android.support.v4.app.Fragment fragment;
    if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){
        fragment = new ProfileFragment();
    }else {
        fragment = new LoginFragment();
    }
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame,fragment);
    ft.commit();
}

OR

private void initFragment(){
    android.app.Fragment fragment;
    if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){
        fragment = new ProfileFragment();
    }else {
        fragment = new LoginFragment();
    }
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame,fragment);
    ft.commit();
}

So if you are using support libraries then use getSupportFragmentManager() and it's supported other methods which are related to support library or else for android app fragment usage don't use support library function. It will create issues with 'Type mismatch'. And this is highly recommended.

Support library imports for fragment trasaction:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

Android library imports for fragment transactions:

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

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