Android RemoveViewAt不删除每个视图
每次玩家在我的游戏中移动时,我都会尝试遍历我的RelativeLayout并删除除我的地图之外的所有视图,而我的地图可以处理所有点击。我在使用gameActivityRelativeLayout.RemoveAllView时发现;它会弄乱ontouchevent代码。我循环遍历每个子视图并将它们全部删除,但不知何故,它们并没有全部删除。我已经进行了广泛的搜索并尝试了许多方法,但我无法找到答案Android RemoveViewAt不删除每个视图,android,view,Android,View,每次玩家在我的游戏中移动时,我都会尝试遍历我的RelativeLayout并删除除我的地图之外的所有视图,而我的地图可以处理所有点击。我在使用gameActivityRelativeLayout.RemoveAllView时发现;它会弄乱ontouchevent代码。我循环遍历每个子视图并将它们全部删除,但不知何故,它们并没有全部删除。我已经进行了广泛的搜索并尝试了许多方法,但我无法找到答案 if (GameActivity.gameActivityRelativeLayout != null)
if (GameActivity.gameActivityRelativeLayout != null) {
activity_game.runOnUiThread(new Runnable() {
@Override
public void run() {
//remove all views except for mapImageView
for (int i = 0; i < GameActivity.gameActivityRelativeLayout.getChildCount(); i++){
View tmpView = GameActivity.gameActivityRelativeLayout.getChildAt(i);
if (!(tmpView instanceof MapImageView)){ //remove all views other than mapImageView
GameActivity.gameActivityRelativeLayout.removeViewAt(i);
}
}
Log.i("jay", "====Below view should only be mapImageView1====");
for (int i = 0; i < GameActivity.gameActivityRelativeLayout.getChildCount(); i++){
View tmpView = GameActivity.gameActivityRelativeLayout.getChildAt(i);
Log.i("jay", "View: " + tmpView + "tmpView.getTag(R.id.TAG_ID): " + tmpView.getTag(R.id.TAG_ID));
}
Log.i("jay", "====Above view should only be mapImageView1====");
//removing all and then readding mapImageView screwed up the ontouchevent code
//GameActivity.gameActivityRelativeLayout.removeAllViews();
//GameActivity.gameActivityRelativeLayout.addView(GameActivity.mapImageView);
//add all of the mob/npcs/enemy players/tradeskills/etc. to the screen
for (ImageView temp : MapImageView.tmpImageViewPool) {
if (temp.getParent() != GameActivity.gameActivityRelativeLayout){
temp.invalidate();
GameActivity.gameActivityRelativeLayout.addView(temp);
}
}
GameActivity.gameActivityRelativeLayout.invalidate();
GameActivity.mapImageView.invalidate();
}
});
}
原因是当我们像这样开始删除时,子位置不是唯一的。删除位置0处的视图后。位置1处的视图变为位置0。所以有一种方法可以做到这一点
int count = GameActivity.gameActivityRelativeLayout.getChildCount();
while(count>1) {
for (int i = 0; i < GameActivity.gameActivityRelativeLayout.getChildCount(); i++){
View tmpView = GameActivity.gameActivityRelativeLayout.getChildAt(i);
if (!(tmpView instanceof MapImageView)) { //remove all views other than mapImageView
GameActivity.gameActivityRelativeLayout.removeViewAt(i);
}
}
count = GameActivity.gameActivityRelativeLayout.getChildCount();
}
如果您希望iterate Child通过某些功能删除其中一些,例如,所有ImageView或具有某个标记的视图-向后执行迭代:
for (int i = someParentLayout.getChildCount() - 1; i > -1; i--) {
View v = someParentLayout.getChildAt(i);
if (v instanceof ImageView) {
someParentLayout.removeViewAt(i);
}
}
在这种情况下,每次迭代后,孩子的数量都会减少,但这不会影响您!非常感谢你。我不知道它是以这样的方式被移除的。
for (int i = someParentLayout.getChildCount() - 1; i > -1; i--) {
View v = someParentLayout.getChildAt(i);
if (v instanceof ImageView) {
someParentLayout.removeViewAt(i);
}
}