4

我正在第一次尝试适用于 Android 的 RoboGuice2(以及 Guice),现在我被卡住了。我一直无法找到一个如何做到这一点的例子,并且希望有人能向我展示正确的解释方法。我想@Inject 一个将字符串作为构造函数中的参数的对象。下面的例子:

public class MyActivity extends RoboFragmentActivity {

    @Inject MyObject obj;

    public void onCreate(Bundle savedInstanceState) {
       super.onCreate();
       obj.print();
    }
}



public class MyObject {

    private String name;

    @Inject
    public MyObject(String name) {
       this.name = name;
    }


    public void print() {
        Log.d("debug", this.name);
    }
}

我会非常感谢一个例子和对此的解释。

4

1 回答 1

2

I'm not sure if it's possible to inject an object with RoboGuice while passing a parameter to its constructor (and this is certainly not encouraged). You might want to consider just changing whatever method you call on that object that writes to the file system to take in that String parameter. If you don't like that option, you can just have a public method to set that parameter before calling the write function.

Ex:

@Inject
private MyClass myClass;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate();
    myClass.setFileName("somefile.txt");
    myClass.writeToFile();
}

Or

@Inject
private MyClass myClass;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate();
    myClass.writeToFile("somefile.txt");
}

EDIT:

So after doing some research I'm taking back my statement about this not being encouraged. From the examples I've seen, your code looks to be be mostly correct. This Link provided the most complete example I could find. It seems that there are two options if you want to inject a String into the constructor. you can set it up in you app config bindings (which essentially creates a singleton that you probably don't want). The second option is to create a Provide (similar to Factory) and use that provider. Both of these options are outlined in the article above.

于 2012-12-13T00:14:40.343 回答