2017-08-24 85 views
-2

我添加视图到rootview以这种方式无法从根视图中删除视图

private RelativeLayout addThisView; 
private View rootView; 

LayoutInflater inflater = LayoutInflater.from(mContext); 
addThisView = (RelativeLayout) inflater.inflate(R.layout.loading_temp_cover, null, false); 
if(rootView instanceof FrameLayout){ 
    ((FrameLayout)rootView).addView(addThisView); 
} 

试图从根视图中删除视图

/* remove view from the root view start */ 

rootView = ((Activity) mContext).getWindow().getDecorView().findViewById(android.R.id.content); 
RelativeLayout loadingTempCoverRelative =(RelativeLayout) rootView.findViewById(R.id.loadingTempCoverRelative); 

if(loadingTempCoverRelative!=null){ 
    if(rootView instanceof FrameLayout){ 
     ((FrameLayout)rootView).removeView(loadingTempCoverRelative); 
    } 
} 

/* remove view from the root view end */ 

,然后当我检查loadingTempCover是存在(下面的代码)。它仍然存在.. 我调试看看;当到达并完成removeView()函数时,它不会产生任何效果。我仍然可以在rootview中看到loadingTempCover布局。我不明白我在哪里做错了..

rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content); 
RelativeLayout loadingTempCoverRelative =(RelativeLayout) rootView.findViewById(R.id.loadingTempCoverRelative); 

if(loadingTempCoverRelative!=null){ 
    loadingTempCoverRelative.setVisibility(loadingTempCoverRelative.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE); 
    return; 
} 
+0

我理解的问题。怎么可能android studio导致这个问题。有趣的..我重建项目和removeView函数正在工作。顺便说一句,我不明白你为什么把我的问题标记为没用?这太有趣了.. – fthopkins

回答

0

尝试直接通过视图获取父:

rootView = ((Activity) mContext).getWindow().getDecorView().findViewById(android.R.id.content); 
RelativeLayout loadingTempCoverRelative =(RelativeLayout) rootView.findViewById(R.id.loadingTempCoverRelative); 

ViewGroup parent = loadingTempCoverRelative.getParent(); 

if(loadingTempCoverRelative!=null){ 
    if(rootView instanceof FrameLayout && parent != null){ 
     parent.removeView(loadingTempCoverRelative); 
    } 
} 

应测试条件if(rootView instanceof FrameLayout)为好,这个问题也许是这里。

希望它有帮助。

+0

感谢您的回复。它与条件或getParent无关。 Android工作室导致此问题。我重建了这个项目,现在问题没有了。 – fthopkins

0

使用以下代码

((ViewGroup) rootView.getParent()).removeView(namebar);