incompatible types: HomeFragment cannot be converted to Fragment in Android

后端 未结 9 1608
轻奢々
轻奢々 2020-12-01 15:57

I\'m getting an error in this part of code:

private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragm         


        
相关标签:
9条回答
  • 2020-12-01 16:22

    If you are using support library, you should ensure to import both Fragment and FragmentManager from the support library. You will also need to ensure to load the support fragment manager.

    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    //other imports here...
    
    public class SomeActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_some);
    
            FragmentManager fm = getSupportFragmentManager();
            Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    
            if(fragment == null) {
                fragment = new SomeFragment();
                fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
            }
    
        }
    }
    
    0 讨论(0)
  • 2020-12-01 16:24

    use getSupportFragmentManager() Instead of getFragmentManager()

    getSupportFragmentManager()
        .beginTransaction()
        .replace(in.jama.app.R.id.container, new Fragment())
        .commit();
    
    0 讨论(0)
  • 2020-12-01 16:25

    import android.app.Fragment; works with getFragmentManager() method but before you have to remove the import android.support.v4.app.Fragment;

    0 讨论(0)
提交回复
热议问题