我正在使用ViewStubs在我的布局中加载显示数据。由于我使用ButterKnife绑定(bind)布局组件,因此我有一些自定义类,用于保存各个viewtub布局的组件,例如,如下所示的一个viewtub。

 <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);
}

在我的 fragment 的两个不同位置调用了上述方法。第一次正确充气,但是第二次以java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent失败。

我该如何处理这种情况。

最佳答案

Android会像这样膨胀ViewStub:

  • 最初以与任何其他View
  • 相同的方式向View层次结构添加ViewStub
  • 调用inflate时,以指定的布局替换该 View 。

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

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

    10-08 09:33
    查看更多