1

我有一个ViewGroup活动,我想用它来替换两个片段,具体取决于用户流(所以我将显示一个片段或另一个片段)。在使用Roboguice依赖注入时编程实例化Android片段

(...) 
    <FrameLayout 
     android:id="@+id/fragment_container" 
     android:layout_width="match_parent" 
     android:layout_height="276dp" 
     android:layout_gravity="center_horizontal|bottom"> 
    </FrameLayout> 
    (...) 

要设置的片段,我用下面的代码:

private void setBottomFragment(Fragment fragment) { 
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
    transaction.replace(R.id.fragment_container, fragment); 
    transaction.addToBackStack(null); 
    transaction.commit(); 
} 

如果我实例化片段自己新的,它的工作原理:

setBottomFragment(new InformationFragment()); 

不过,我不我不想自己实例化它。我希望我的片断实例由我依赖管理框架来管理(我使用Roboguice

所以我喜欢做这样的事情:

@ContentView(R.layout.activity_scan) 
public class ScanActivity extends RoboFragmentActivity { 

    @InjectFragment(R.id.information_fragment) 
    private InformationFragment informationFragment; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setBottomFragment(informationFragment); 
    } 
} 

通过这样做,我会也可以在我的Fragments上使用依赖注入,而不必自己查找组件。

public class InformationFragment extends RoboFragment { 

     // I'll have an event handler for this button and I don't want to be finding it myself if I can have it injected instead. 
     @InjectView(R.id.resultButton) 
     private Button resultButton; 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
      // Inflate the layout for this fragment 
      return inflater.inflate(R.layout.fragment_information, container, false); 
     } 
    } 

所以基本上我的问题是:我怎么能实例片段programaticly而使用像Roboguice依赖注入框架?

在Roboguice文档中我可以找到的所有DI都带有片段的示例,片段最初与视图一起呈现,之后不会动态添加,就像我试图做的那样。这导致我相信我在组件的生命周期或Roboguice处理DI的方式中缺少某些东西。

任何想法解决这个或指针在正确的方向将是非常有益的。

+0

你实现生命周期方法onCreateView在你的片段,在布局被夸大? –

+0

是的,我创建了该方法。或者,当我创建片段时,IDE做到了。我将编辑原始问题以说明这一点。 – redwulf

回答

0

我自己找到答案,因为它可能对别人有帮助,我会在这里发布。

这比我预期的要简单得多(而且有点显而易见)。由于片段不是活动首次加载时的视图的一部分,因此我们不能使用@InjectFragment。应该使用@Inject来代替,因此该片段被视为与任何其他非视图相关性一样。

这意味着我的活动应该是这样的:

@ContentView(R.layout.activity_scan) 
public class ScanActivity extends RoboFragmentActivity { 

    @Inject // This is all that needs to change 
    private InformationFragment informationFragment; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setBottomFragment(informationFragment); 
    } 
} 

这简单......