【问题标题】:Injected views remain null for inflated layouts对于膨胀的布局,注入的视图保持为空
【发布时间】:2012-07-02 10:41:33
【问题描述】:

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

【问题讨论】:

    标签: android-layout layout-inflater roboguice


    【解决方案1】:

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

    【讨论】:

    • 感谢您的精彩回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多