androidx.fragment.app.Fragment не может быть преобразован в android.app.Fragment

#android #android-studio #android-fragments #dependencies #fragment

#Android #android-studio #android-фрагменты #зависимости #фрагмент

Вопрос:

У меня есть файл фрагмента. Появляется сообщение об ошибке

«ошибка: несовместимые типы: androidx.fragment.app.Fragment не может быть преобразован в android.app.Fragment. FragmentTransaction.replace(R.id.frame_layout, фрагмент).addToBackStack(null);»

Я знаю, что с моим файлом build.gradle что-то не так, но я не знаю, какую зависимость мне следует использовать. Я уже прочитал документацию и связанные с ней вопросы, но некоторые зависимости устарели. Это мой файл MainActivity:

 package com.example.notesapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        replaceFragment(HomeFragment.newInstance(), true);
    }

    @SuppressLint("ResourceType")
    public void replaceFragment(Fragment fragment, Boolean istransition){
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if(istransition) {
            fragmentTransaction.setCustomAnimations(android.R.anim.slide_out_right, android.R.anim.slide_in_left);
        }

        fragmentTransaction.replace(R.id.frame_layout, fragment).addToBackStack(null);
    }
}
 

И это мой файл build.gradle

 plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.notesapp"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4. '
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

    //material design
    implementation 'com.google.android.material:material:1.2.1'

    //circle image view
    implementation 'de.hdodenhof:circleimageview:3.1.0'

    //scalable unit text size
    implementation 'com.intuit.ssp:ssp-android:1.0.6'

    //scalable unit size
    implementation 'com.intuit.sdp:sdp-android:1.0.6'

    //room database
    implementation 'androidx.room:room-runtime:2.2.5'
    annotationProcessor 'androidx.room:room-compiler:2.2.5'

    implementation 'com.intuit.ssp:ssp-android:1.0.6'

}
 

Спасибо

Ответ №1:

Использовать

 import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction
 

Вместо

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

Комментарии:

1. getSupportFragmentManager вместо обычного (не- androidx )

Ответ №2:

вопрос в том, что это HomeFragment — расширение встроенной Fragment или androidx версии? он должен расширить androidx версию. и тогда вы должны использовать getSupportFragmentManager

 FragmentManager fragmentManager = getSupportFragmentManager();
 

тогда ваша среда разработки должна предложить вам исправить импорт или даже сделать это за вас — не должно использоваться никакого android.app.Fragment... импорта, только androidx.fragment... строки / пакеты

Комментарии:

1. мой домашний фрагмент расширяет версию фрагмента

2. extends Fragment , но какой? проверьте импорт поверх файла класса. ваша ошибка предполагает, что ваша HomeFragment расширенная androidx версия (должна быть), но вы используете встроенную FragmentManager вместо androidx one — getFragmentManager без Support ключевого слова в середине. эти две версии Fragment s несовместимы, выберите один из способов. стоит сказать, что встроенный в android.app настоящее время устарел, поэтому я настоятельно рекомендую androidx поддерживать версию как lib

3. рассмотрите возможность голосования / принятия ответа, если это полезно 🙂 удачи!