【问题标题】:Accessing Guice singleton in a constructor在构造函数中访问 Guice 单例
【发布时间】:2012-03-08 23:06:21
【问题描述】:

我正在使用 Guice(Roboguice v2 与 Guice v3 完全相同),我对它有点陌生。

我有一个单身..

@Singleton
Accounts
{
    public Account[] getAllAccounts()
    {
        // Stuff
    }
}

而且我还有一个类需要在其构造函数中访问上述内容..

public class AccountListAdapter extends ArrayAdapter<Account>
{
    public AccountListAdapter(Context c)
    {
        super(c, R.layout.account_list_row, R.id.accountName, accounts.getAllAccounts());
    }

    ...
}

如何访问上面用作 super() 调用的最后一个参数的 Accounts 单例?因为构造函数将在创建任何实例变量之前执行。

谢谢!

【问题讨论】:

  • 您是否在 Activity onCreate() 期间创建 AcountListAdapter?

标签: guice


【解决方案1】:

这两种方法都可以处理。

首先,您可以将适配器直接注入到您的活动中。这将包括当前 Context 以及单例:

public class ExampleActivity extends RoboActivity{

     @Inject
     private AccountListAdapter accountListAdapter;

     ....
     //then register it with your listView in your onCreate()
 }

请记住,您需要添加以下注释:

public class AccountListAdapter extends ArrayAdapter<Account>
{
    @Inject
    public AccountListAdapter(Context c, Accounts acconts)
    {
        super(c, R.layout.account_list_row, R.id.accountName, accounts.getAllAccounts());
    }

    ...
}

其次,你可以在 onCreate() 过程中自己构造对象:

public class ExampleActivity extends RoboActivity{

     @Inject
     private Account accounts;

     public void onCreate(Bundle savedInstanceState) { 
         super.onCreate(savedInstanceState); 
         setContentView(R.layout.main);

         AccountListAdapter accountListAdapter = new AccountListAdapter(this, accounts);

     //then register it with your listView
 }

您可能需要扩展 Roboguice ListActivity 而不是 RoboActivity 才能成功使用 ListActivity。让我知道这是否适合您。

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多