0

我可以在将被膨胀的布局中包含的元素上使用 Roboguice @InjectView 吗?在我看来,这些元素最初被声明为 @Nullable 似乎是正确的,因为它们在膨胀完成之前是未知的。但是在膨胀之后,元素仍然保持为空,直到完成“findViewById”。

举个例子:我使用下面的代码来注入一个可以为空的文本视图(标题),它包含在 title_layout 中,它会在主布局中膨胀:

@Nullable @InjectView(R.id.title) TextView title;
@InjectView(R.id.title_info) LinearLayout titleContainer;

然后在 onCreate() 方法中我这样做:

setContentView(R.layout.main);
inflater.inflate(R.layout.title_layout, titleContainer);

我有main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:id="@+id/title_info">
  </LinearLayout>
</LinearLayot>

title_layout.xml

  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:id="@+id/title" 
      android:text="my title" />
</LinearLayot>

膨胀视图的标题 (TextView) 始终为null,即使在 title_layout 膨胀之后也是如此。

这样做:

setContentView(R.layout.main);
inflater.inflate(R.layout.title_layout, titleContainer);
title = (TextView)findViewById(R.id.title);\

解决问题。

有什么方法可以使用@InjectView?

4

1 回答 1

2

我遇到了同样的问题——原来我是在扩展Activity而不是RoboActivity,所以它从来没有处理过注射。

于 2012-09-04T15:09:21.660 回答