gpt4 book ai didi

android - 如何检查 viewStub 是否已经膨胀?

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

我没有发现任何 bool 方法可以完成这项任务。我可以通过检查 viewStubid 是否更改为指定为 inflatedid 的那个来做到这一点吗?

Java代码:

    protected void plantViewTree() {
// TODO Auto-generated method stub

ViewStub mViewstub = (ViewStub) findViewById(R.id.viewStub00);

if (mViewStub is inflated) {
//do somthing
}else
mViewstub.inflate();

}

更新对 eOutput 的评论

根据这段代码,toast 总是显示它的消息,这意味着由于 mViewStub 被分配给 findViewById 它永远不会为空,除了底层 alyout 中的 viewstub View 不可用。有什么建议吗?

protected void plantViewTree() {
// TODO Auto-generated method stub
ViewStub mViewstub = (ViewStub) findViewById(R.id.viewStub00);
if (mViewstub != null)
Toast.makeText(getApplicationContext(), "view is inflated",
Toast.LENGTH_LONG).show();
else
mViewstub.inflate();
}

最佳答案

我们可以查看ViewStub源码,最重要的方法是inflate()

 public View inflate() {
final ViewParent viewParent = getParent();

if (viewParent != null && viewParent instanceof ViewGroup) {
if (mLayoutResource != 0) {
final ViewGroup parent = (ViewGroup) viewParent;
final LayoutInflater factory;
if (mInflater != null) {
factory = mInflater;
} else {
factory = LayoutInflater.from(mContext);
}
final View view = factory.inflate(mLayoutResource, parent,
false);

if (mInflatedId != NO_ID) {
view.setId(mInflatedId);
}

final int index = parent.indexOfChild(this);
parent.removeViewInLayout(this);

final ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (layoutParams != null) {
parent.addView(view, index, layoutParams);
} else {
parent.addView(view, index);
}

mInflatedViewRef = new WeakReference<View>(view);

if (mInflateListener != null) {
mInflateListener.onInflate(this, view);
}

return view;
} else {
throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
}
} else {
throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
}
}

注意这一行 parent.removeViewInLayout(this) ,它在 inflate 之后在布局中被删除了。所以我们可以通过这种方式检查 viewStub 是否已经膨胀。

if (mViewStub.getParent() != null) {
mViewStub.inflate();
} else {
mViewStub.setVisibility(View.VISIBLE);
}

关于android - 如何检查 viewStub 是否已经膨胀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23783101/

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