Dragger2系列--第一节 最简教程

1 添加依赖库:

在项目的build.gradle中添加:
    classpath 'me.tatarka:gradle-retrolambda:3.2.4'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
在app的build.gradle中添加:
     compile 'com.google.dagger:dagger:2.11-rc1'
     annotationProcessor 'com.google.dagger:dagger-compiler:2.11-rc1'
     compile 'org.glassfish:javax.annotation:10.0-b28'

2 创建User类:

package lincoln.com.myapplication;
import javax.inject.Inject;
import dagger.Module;

@Module
public class User {
    private String name;

    @Inject
    public User() {
        this.name = "小美";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

3 创建MainComponent:

package lincoln.com.myapplication;
import dagger.Component;
/**
 * Created by lincoln on 2017/7/10.
 */
@Component
public interface MainComponent {
    void inject(MainActivity activity);
}

4 Activity代码:

package lincoln.com.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import javax.inject.Inject;

public class MainActivity extends AppCompatActivity {
    private Button btn;

    @Inject User mUser;

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


        DaggerMainComponent.builder().build().inject(this);

        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn.setText(mUser.getName());
            }
        });
    }
}

如果找不到DaggerMainComponent,执行rebuild一下就可以了。

------第一节简单实例完成-----------------------

你可能感兴趣的:(Dragger2系列--第一节 最简教程)