7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Dagger2導入

Last updated at Posted at 2016-09-26

環境

AndoirdStudio2.2
Gradle2.14.1

Gradle

rootのbuild.gradleに1行追加

build.gradle

dependencies {
    classpath 'com.android.tools.build:gradle:2.2.0'
    // APT Plugin
    classpath 'com.uphyca.gradle:gradle-android-apt-plugin:0.9.4'
}

appのbuild.gradleに3行追加

app/build.gradle

apply plugin: 'com.android.application'

// APT Plugin 'com.android.application'以降に追加しなければいけないので注意
apply plugin: 'android-apt'

dependencies {

    // Dagger2
    compile 'com.google.dagger:dagger:2.2'
    apt 'com.google.dagger:dagger-compiler:2.2'
}

Module

Module用のクラスを作成

HelloModule.java

@Module
public class HelloModule {
    @Provides
    Hello provideHelloImpl() {
        return new HelloImpl();
    }
}

Component

Componet用インターフェースを作成

ActivityComponent.java
	
@Component(modules = HelloModule.class)
public interface ActivityComponent  {
    void inject(MainActivity activity);
}

インターフェースを作成

sayメソッドだけのインターフェースを作成

Hello.java
	
public interface Hello {
    void say();
}

インターフェースを実装したクラス

helloと出力するだけのメソッド

HelloImpl.java
	
public class HelloImpl implements Hello {
    @Override
    public void say() {
        Log.d("TAG", "hello");
    }
}

MainActivity

1度実行して、DaggerActivityComponentが生成されてから、
実際にInjectして以下のように使ってみる

MainActivity.java
	
public class MainActivity extends AppCompatActivity {

   	@Inject
   	Hello mHello;

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

        DaggerActivityComponent.create().inject(this);
        
        // helloと出力
        mHello.say();
    }
}

以上で終わりですが、実際に通信して使うとこまでを追記しておきます。
Dagger2 + Retrofit2 + RxAndroidで通信してみる
http://qiita.com/MuuKojima/items/8088b43876dc8d3d1745

 

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?