ViewStub必须具有非null的ViewGroup viewParent

时间:2016-11-28 13:10:12

标签: android viewstub

我正在使用ViewStubs在我的布局中加载节目数据。由于我使用ButterKnife来绑定布局组件,因此我有自定义类来保存各个viewstub布局的组件,例如,一个这样的viewstub如下所示。

 <ViewStub
      android:id="@+id/featuredContentStub"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:inflatedId="@+id/featuredContent"
      android:layout="@layout/featured_content" />

处理@layout/featured_content组件的类如下:

public class FeaturedContentView {
        @BindView(R.id.art)
        ImageView art;
        @BindView(R.id.shade)
        View shade;
        @BindView(R.id.title)
        TextView featuredTitle;
        @BindView(R.id.performer)
        TextView performer;
        @BindView(R.id.featured_title)
        KerningTextView featuredText;
        @BindView(R.id.play_button)
        Button play;
        @BindView(R.id.shareText)
        TextView shareText;
        @BindView(R.id.addToFavorites)
        ImageView addToFavs;

        FeaturedContentView(View view) {
            ButterKnife.bind(this, view);
        }
    }

我像这样膨胀布局:

if (viewstub != null) {
        View view = viewstub.inflate();
        featuredContentView = new FeaturedContentView(view);
}

在我的片段中的两个不同位置调用上述方法。它第一次正确膨胀但第二次引用java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent时失败。

我该如何处理这种情况。

1 个答案:

答案 0 :(得分:4)

Android像这样膨胀ViewStub:

  1. 最初以与任何其他View
  2. 相同的方式将ViewStub添加到View层次结构
  3. 在致电inflate
  4. 时,将该视图替换为指定的布局

    这意味着,当您第二次调用代码时,原始ViewStub对象与View层次结构长期分离,并且已被完整视图替换。

    就个人而言,我认为ViewStub的当前形式非常不方便,特别是在使用ButerKnife时。幸运的是,类本身非常简单,您始终可以创建一个自定义类,它会执行相同的操作并向其添加任何所需的方法(例如isInflatedaddInflateCallback等)。顺便说一下,Android支持库开发人员也是如此。

相关问题