gpt4 book ai didi

android - ViewStub 必须有一个非空的 ViewGroup viewParent

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:41:48 25 4
gpt4 key购买 nike

我正在使用 ViewStubs 在我的布局中加载显示数据。因为我使用 ButterKnife 来绑定(bind)布局组件,所以我有自定义类来保存各个 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);
}

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

我该如何处理这种情况。

最佳答案

Android 像这样扩充 ViewStub:

  1. 最初以与任何其他 View 相同的方式将 ViewStub 添加到 View 层次结构
  2. 在调用 inflate 时用指定的布局替换该 View 。

这意味着,当您的代码被第二次调用时,原始 ViewStub 对象早已从 View 层次结构中分离出来,并且已经被完整的 View 所取代。

就我个人而言,我认为当前形式的 ViewStub 非常不方便,尤其是在使用 ButerKnife 时。幸运的是这个类本身非常简单,你总是可以创建一个自定义类,它做同样的事情并向它添加任何需要的方法(比如 isInflated, addInflateCallback 等) .顺便说一下,Android 支持库开发人员也做了同样的事情。

关于android - ViewStub 必须有一个非空的 ViewGroup viewParent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40845147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com