android - 使用 roboguice 脱离 roboactivity

标签 android android-fragments guice roboguice

<分区>

我有一个 roboactivity,我在其中注入(inject)了一些东西,例如资源和 View 。我在我的应用程序中使用了一些 fragment 类。这些 fragment 必须扩展 fragment 。这是我的东西:

当按下按钮时,我会创建一个新 fragment :

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

fragmentTransaction.replace(R.id.content_frame,Fragment.instantiate(this,fragments[position]));
fragmentTransaction.commit();

我的 fragment 看起来像这样:

public class MyLists extends Fragment {
    @InjectView(R.id.myview)
    private TextView myview;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {      
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.my_lists_fragment, null);

        MyRepo repo= new MyRepo ();

        myview.setText(repo.getSomething());
        return root;
    }
}

InjectView 不工作。我找不到它不起作用的原因。谁能帮我解决这个问题?

最佳答案

注入(inject)发生在 onViewCreated 期间,它在 onCreateView 之后。将您的代码移动到 onViewCreated

Activity 上有 setContentView 可以进行注入(inject)。在 fragment 上,您返回 View ,因此 robojuice 直到稍后才能知道将其用于注入(inject)。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {      
    ViewGroup root = (ViewGroup) inflater.inflate(R.layout.my_lists_fragment, null);
    // Here you've inflated something, but robojuice has no way of knowing
    // that's the fragments view at this point, and no base method has been called
    // that robojuice might use to find your View.
    // So myview is still null here:
    myview.setText(repo.getSomething());
    return root;
}

关于android - 使用 roboguice 脱离 roboactivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23847333/

相关文章:

java - JUnit 测试中的 Guice 注入(inject)器

java - 创建 MutableGuiceKeyToInstanceMap 的最简单方法?

android - 应用程序ID和程序包ID不同,当用户对其进行更新时会崩溃

java - 使用带有 BLOB 数据的游标加载器

java - BackStackEntryCount 和 FragmentManager

android - 如何从 MenuItem 导航到 fragment (Android)?

Android jar 使用有效的 keystore 未签名,需要 SHA1 证书吗?

android - Intellij IDEA 中资源文件的快速切换

android - 将 ActivityGroup 应用程序转换为使用 Fragments/FragmentGroup

Scala/Akka/Guice 动态注入(inject) child Actor