Roboguice 中最常用的一种绑定为Linked Bindings,将某个类型映射到其实现。这里我们使用引路蜂二维图形库中的类为例,引路蜂二维图形库的使用可以参见Android简明开发教程八:引路蜂二维图形绘制实例功能定义。

使用下面几个类 IShape, Rectangle, MyRectangle, MySquare, 其继承关系如下图所示:

下面代码将IShape 映射到MyRectangle

public class Graphics2DModule extends AbstractAndroidModule{  @Override protected void configure() {  bind(IShape.class).to(MyRectangle.class);  }}

此时,如果使用injector.getInstance(IShape.class) 或是injector 碰到依赖于IShape地方时,它将使用MyRectangle。可以将类型映射到它任意子类或是实现了该类型接口的所有类。也可以将一个实类(非接口)映射到其子类,如

bind(MyRectangle.class).to(MySquare.class);

下面例子使用@Inject 应用IShape.

public class LinkedBindingsDemo extends Graphics2DActivity{ @Inject IShape  shape; protected void drawImage(){ /*** The semi-opaque blue color in* the ARGB space (alpha is 0x78)*/Color blueColor = new Color(0x780000ff,true);/*** The semi-opaque yellow color in the* ARGB space ( alpha is 0x78)*/Color yellowColor = new Color(0x78ffff00,true); /*** The dash array*/int dashArray[] = { 20 ,8 };graphics2D.clear(Color.WHITE);graphics2D.Reset();Pen pen=new Pen(yellowColor,10,Pen.CAP_BUTT,Pen.JOIN_MITER,dashArray,0);SolidBrush brush=new SolidBrush(blueColor);graphics2D.setPenAndBrush(pen,brush);graphics2D.fill(null,shape);graphics2D.draw(null,shape); } }

使用bind(IShape.class).to(MyRectangle.class),为了简化问题,这里定义了MyRectangle和MySquare都带有一个不带参数的构造函数,注入具有带参数的构造函数类用法在后面有介绍。

public class MyRectangle extends Rectangle{ public MyRectangle(){ super(50,50,100,120); }  public MyRectangle(int width, int height){ super(50,50,width,height); }}...public class MySquare extends MyRectangle {  public MySquare(){ super(100,100); }  public MySquare(int width){ super(width,width); } }

Linked bindings 允许链接,例如


public class Graphics2DModule extends AbstractAndroidModule{  @Override protected void configure() { bind(IShape.class).to(MyRectangle.class); bind(MyRectangle.class).to(MySquare.class);  }}


此时当需要IShape 时,Injector返回MySquare 的实例, IShape->MyRectangle->MySquare

本例下载



更多相关文章

  1. Android的View组件的几大子类
  2. Android(安卓)如何建立AIDL
  3. UI组件之 ProgressBar及其子类(一)ProgressBar进度条的使用
  4. Android在标准linux基础上对休眠唤醒的实现(二)
  5. Android简明开发教程十四:Context Menu 绘制几何图形
  6. Android跨进程数据通讯-剪切板Clipboard
  7. [置顶] Android(安卓)设置铃声分析
  8. Android(安卓)okHttp 实战(三):okHttp网络请求之Json解析
  9. Android在标准linux基础上对休眠唤醒的实现

随机推荐

  1. 意派Epub360丨不要小瞧轻量级H5小游戏的
  2. 选择万能码不后悔(安全扫码专业委员会)
  3. fl studio破解版及20中文破解版补丁附加
  4. 追格企业官网主题(小程序+PC+H5)助你快速搭
  5. 小鸟云虚拟主机和云服务器和裸金属服务器
  6. 简单计算器
  7. JavaScript实现简单计算器
  8. 【php】while/for循环,网络请求
  9. laravel 路由
  10. laravel 视图view