Android LinearLayout.removeViewAt(int i)抛出异常?

时间:2016-06-03 17:07:55

标签: android

我有以下代码:

for (int i = 0; i < linearLayout.getChildCount() - 5; i++) //IN this code, please assume the child count is 10;
{
    View v = linearLayout.getChildAt(i);
    Standard.Loge("REMOVING: " + i + " " + (v == null));
    linearLayout.removeViewAt(i);
}

这输出以下内容:

REMOVING: 0 false
REMOVING: 1 false
REMOVING: 2 true

应用程序崩溃,即使索引2 - 4的视图尚未删除,也会抛出此错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.unFocus(android.view.View)' on a null object reference
    at android.view.ViewGroup.removeViewInternal(ViewGroup.java:4937)
    at android.view.ViewGroup.removeViewAt(ViewGroup.java:4899)
    at (((The last line in the for loop above)))

看起来这些视图是空的,即使getChildCount注册了视图存在,我的猜测是这导致removeChildAt崩溃。我在java中动态添加视图,所以我无法使用findViewByID。我真的很茫然。如何修复此崩溃,以便删除这些视图?

1 个答案:

答案 0 :(得分:7)

我认为你实际上只想删除元素0.当你删除其中一个元素时,它们都会向后移动。因此,元素1变为0,2变为1,等等。

此代码应该有效:

for (int i = 0; i < linearLayout.getChildCount() - 5; i++) //IN this code, please assume the child count is 10;
{
    View v = linearLayout.getChildAt(0);
    Standard.Loge("REMOVING: " + 0 + " " + (v == null));
    linearLayout.removeViewAt(0);
}