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

我没有find任何布尔方法做这个任务。 我可以通过检查viewStubid viewStub改变为指定的inflatedid

Javacode:

  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视图不可用。 有什么build议么。?

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

Solutions Collecting From Web of "如何检查viewStub是否已经膨胀?"

我们可以查看ViewStub源代码,最重要的方法是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.so之后,它已经在布局中移除了,所以我们可以通过这种方式来检查viewStub是否已经膨胀了。

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

从谷歌注意到:

当ViewStub变得可见时,或者当调用inflate()时,布局资源被充满。

所以你可以检查可见性(甚至检查它是否为“空”)。

调用你的yourViewStub.visibility(View.VISIBLE)你不需要检查它是否膨胀。

 if (mViewStub.getParent() != null) { //have not been inflated mViewStub.inflate(); } else { //already inflated } 

我用flags解决了它。 我宣布全局布尔variablesisInflatedBefore初始设置为false

码:

 //declaration of the variable private boolean isInflatedBefore = false ... ... ... protected void plantViewTree() { // TODO Auto-generated method stub ViewStub mViewstub = (ViewStub) findViewById(R.id.viewStub00); if (! isInflatedBefore) { isInflatedBefore = true; mViewstub.inflate(); }else { //some code }