22

パッケージandroidx.fragment.app.Fragmentからフラグメントを注入する方法は?

コードに依存関係を挿入するために、 dagger-androidフレームワークを使用しています。

ドキュメントにあるように、フラグメントを注入するためにこれを行います

@Override
public void onAttach(Activity activity) {
    AndroidInjection.inject(this);
    super.onAttach(activity);
    // ...
}

問題は、AndroidSupportInjectionクラスがパッケージ android.support.v4.app.Fragment のフラグメントのみを受け入れるか、AndroidInjectionクラスを使用する場合、パッケージ android.app.Fragment のフラグメントのみを受け入れ、androidx.fragment のフラグメントを使用したいことです。 app.Fragment パッケージ。

また、DaggerFrament はandroid.support.v4.app.Fragmentから拡張され、androidx のフラグメントを使用したい

また、 HasSupportFragmentInjectorを実装しようとすると、このインターフェイスは android.support のフラグメントを使用します

4

7 に答える 7

9

以下のコードを gradle.properties に追加します

android.useAndroidX=true
android.enableJetifier=true

そして、フラグメントに注入しようとしている場合は、次のものに置き換える必要がありAndroidInjection.inject(this)ますAndroidSupportInjection.inject(this)

于 2019-02-04T12:25:54.990 に答える
0

私の特定の問題の解決策は、android dagger クラスを拡張するのではなく、インターフェイスとして使用することでした。

class MyFragment() : HasSupportFragmentInjector {

    @Inject
    lateinit var childFragmentInjector: DispatchingAndroidInjector<Fragment>

    override fun onAttach(context: Context?) {
        AndroidSupportInjection.inject(this)
        super.onAttach(context)
    }

    override fun supportFragmentInjector(): AndroidInjector<Fragment> {
        return childFragmentInjector
    }

........

}

私の活動へ

class MyActivity : HasSupportFragmentInjector {
    @Inject
    internal lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
    }

    override fun supportFragmentInjector(): AndroidInjector<Fragment> = fragmentInjector

…… }

また、gradle.propertiesファイルにこれがあります:

android.useAndroidX = true android.enableJetifier = true

于 2019-07-19T16:56:11.050 に答える