2013-07-26 48 views
1

当我按下一个按钮,我想,一个充气观点出现,当我按下同一按钮此视图中消失......我怎么知道,如果一个充气观点存在

ViewGroup parent = (ViewGroup) findViewById(R.id.inflate_place); 
View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.inflate_find, null); 

for(int i=0; i<parent.getChildCount(); ++i) { 
    View nextChild = parent.getChildAt(i); 

    // Here i want that if is the same layout, this disappear 
    if (nextChild.equals(view)) { 
     parent.removeView(nextChild); 
     return; 
    } 
} 

parent.addView(view); 

回答

2

再膨胀了同样的看法并且通常不是最好的方法。

只是一个变量添加到您的活动指向视图要隐藏:

View myView; 

在的onCreate,夸大自己的看法:

myView = LayoutInflater.from(getBaseContext()).inflate(R.layout.inflate_find, null); 

现在,如果你想显示您可以将其添加为您现有的代码:

ViewGroup parent = (ViewGroup) findViewById(R.id.inflate_place); 
parent.add(myView); 

删除可以这样完成:

If (myView.getParent()!=null){ 
    ((ViewGroup) myView.getParent()).removeView(myView); 
} 

切换视图的知名度会工作像:

If (myView.getParent()!=null){ 
    ((ViewGroup) myView.getParent()).removeView(myView); 
} else { 
    ViewGroup parent = (ViewGroup) findViewById(R.id.inflate_place); 
    parent.add(myView); 
} 

你可能想看看View.setVisibility()。这通常用于显示和隐藏视图:http://developer.android.com/reference/android/view/View.html#setVisibility%28int%29

1

您可以从ViewGroup indexOfChild(View view)方法中检查该子项是否存在。它会返回表示组中视图位置的正整数,如果视图不存在于组中,则返回-1。

ViewGroup rootLayout = (ViewGroup) getWindow().peekDecorView(); 
    LayoutInflater li = LayoutInflater.from(this); 
    View myView= li.inflate(R.layout.recorder, null); 
    if(rootLayout.indexOfChild(myView) == -1) 
     rootLayout.addView(myView); 
相关问题