使用Dagger 2注入Androidx Fragments

18

我想使用dagger 2注入我的Androidx片段。在我的活动中,我有:

public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector
{
    @Inject Repository repository;
    @Inject DispatchingAndroidInjector<androidx.fragment.app.Fragment> dispatchingAndroidInjector;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
       
    @Override
    public AndroidInjector<androidx.fragment.app.Fragment> supportFragmentInjector()
    {
        return dispatchingAndroidInjector;
    }
}

问题在于当我尝试构建项目时,出现了以下错误:

error: cannot find symbol class MapBuilder

当我将 androidx.fragment.app.Fragment 修改为 Fragment 并在 DispatchingAndroidInjector 中使用时,便不再出现此错误。

5个回答

15

以下方法适合我:

首先,添加Gradle依赖项以支持Dagger库:

implementation "com.google.dagger:dagger-android-support:2.23.2"

接下来,在您的片段中,作为 androidx.fragment 的子类,以以下方式进行注入:

AndroidSupportInjection.inject(this)

14

3
谢谢您的回答,它起到了作用,但我不得不将Dagger升级到2.16版本。 - mahdi jamshidian
即使我启用了Jetifier Dagger版本2.19,它仍然无法接受Android X Fragment。 - Cyph3rCod3r
6
我正在使用Dagger 2.21与androidx一起使用,它可以工作,但你需要使用AndroidSupportInjection.inject(this),就像@cherif在下面提到的那样。 - LaVepe

10

AndroidX缺少Dagger支持。版本2.21及以上已添加支持。

你可以这样使用 -

implementation 'com.google.dagger:dagger:2.21'
implementation 'com.google.dagger:dagger-android:2.21'
implementation 'com.google.dagger:dagger-android-support:2.21'
kapt "com.google.dagger:dagger-compiler:2.21"
kapt "com.google.dagger:dagger-android-processor:2.21"

除此之外,如果你是第一次使用并从支持库迁移到AndroidX,就像@Saeed Masoumi提到的那样,你还需要在gradle.properties中进行细心的处理。你需要添加以下内容 -

android.useAndroidX=true
android.enableJetifier=true

Jetifier将帮助您在运行时从支持库迁移到AndroidX包。你可以在这里找到最好的答案 - https://dev59.com/_VUK5IYBdhLWcg3wiAUo#52002285


既然你现在在评论,你试过Koin了吗?如果你正在使用Kotlin,并需要进行注入,请比较Koin和Dagger并使用。https://github.com/InsertKoinIO/koin - Jimit Patel
@jimt patel,是的,我试过了。已经卡了两天了,现在问题解决了。谢谢! - Komal
是的,我正在使用 Kotlin,并且肯定会尝试 Koin。 - Komal

4

如之前所建议的,将以下代码添加到您的gradle.properties中

android.useAndroidX=true
android.enableJetifier=true

如果您正在尝试注入Fragment,则必须使用 AndroidSupportInjection.inject(this) 替换 AndroidInjection.inject(this)


2
如果Jetifier未将支持包更改为AndroidX包,则可以从此处下载Jetifier工具,并使用以下命令手动转换android-dagger-support.aar文件。
./jetifier-standalone -i dagger-android-support-<version>.aar -o <output-name>

然后将库添加到您的项目中。这是转换后的HasSupportFragment类。
import androidx.fragment.app.Fragment;
import dagger.android.AndroidInjector;

public interface HasSupportFragmentInjector {
    AndroidInjector<Fragment> supportFragmentInjector();
}

不知何故,Jetifier 工具无法在 AndroidStudio 中转换库。我不得不手动进行转换。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接