Android RoboGuice 使用指南(8):Provider Bindings

jerry Android 2015年08月24日 收藏

如果@Provides方法很复杂的话,可以将这些代码移动到单独的类中。这个类需要实现Guice的Provider 接口,该接口定义如下:

  1. public interface Provider<T> {
  2. T get();
  3. }

为一个generic 接口。

本例我们定义一个PathProvider,用于返回一个Path对象:

  1. public class PathProvider implements Provider<Path>{
  2.  
  3. private String pathdata
  4. = "M 60 20 Q -40 70 60 120 Q 160 70 60 20 z";
  5. @Override
  6. public Path get() {
  7. return Path.fromString(pathdata);
  8. }
  9.  
  10. }

然后在Module中定义从Path类到Provider的绑定:

  1. bind(Path.class).toProvider(PathProvider.class);

然后使用绘制这个Path:

  1. public class ProviderBindingsDemo extends Graphics2DActivity{
  2.  
  3. @Inject Path path;
  4.  
  5. protected void drawImage(){
  6.  
  7. AffineTransform mat1;
  8.  
  9. // Colors
  10. Color redColor = new Color(0x96ff0000, true);
  11. Color greenColor = new Color(0xff00ff00);
  12. Color blueColor = new Color(0x750000ff, true);
  13.  
  14. mat1 = new AffineTransform();
  15. mat1.translate(30, 40);
  16. mat1.rotate(-30 * Math.PI / 180.0);
  17.  
  18. // Clear the canvas with white color.
  19. graphics2D.clear(Color.WHITE);
  20.  
  21. graphics2D.setAffineTransform(new AffineTransform());
  22. SolidBrush brush = new SolidBrush(greenColor);
  23. graphics2D.fill(brush, path);
  24. graphics2D.setAffineTransform(mat1);
  25.  
  26. brush = new SolidBrush(blueColor);
  27. com.mapdigit.drawing.Pen pen
  28. = new com.mapdigit.drawing.Pen(redColor, 5);
  29. graphics2D.setPenAndBrush(pen, brush);
  30. graphics2D.draw(null, path);
  31. graphics2D.fill(null, path);
  32.  
  33. }
  34.  
  35. }