簡體   English   中英

從LinearLayout中刪除視圖或視圖范圍會導致對unFocus的調用中出現NullPointerException

[英]Removing a view or range of views from a LinearLayout causes a NullPointerException in a call to unFocus

我有一個包含LinearLayout的Horizo​​ntalScrollView,用於顯示文件樹狀功能區

 <HorizontalScrollView
        android:id="@+id/content_ribbon_scrollview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:scrollbars="none">

        <LinearLayout
            android:id="@+id/content_file_ribbon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

        </LinearLayout>

    </HorizontalScrollView>

當用戶導航到項目時,項目將添加到LinearLayout中

void addRibbonItem(final Node node) {
        final TextView view = (TextView) getLayoutInflater().inflate(R.layout.shard_ribbon_item, mRibbon, false);
        view.setText(node.getName());

        mRibbon.addView(view);
        mRibbon.postDelayed(() -> mRibonScrollView.fullScroll(View.FOCUS_RIGHT), 17);

單擊某個項目時,應刪除其右側的所有項目。

我嘗試使用removeViewsInLayout方法來執行此操作,以及反復刪除最終視圖。

(忽略缺少邊界檢查)

    view.setOnClickListener(v -> {
        mRibbon.removeViewsInLayout(mRibbon.indexOfChild(view) + 1, mRibbon.getChildCount());
    });


    view.setOnClickListener((v) -> {
        final int index = mRibbon.indexOfChild(view);
        for(int i = 0; i < index; i++) mRibbon.removeViewAt(mRibbon.getChildCount());
    });

這兩種方法都具有相同的例外

 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.removeViewsInternal(ViewGroup.java:4691)
                                                                      at android.view.ViewGroup.removeViewsInLayout(ViewGroup.java:4539)
                                                                      at com.tpb.projects.repo.content.ContentActivity.lambda$-com_tpb_projects_repo_content_ContentActivity_lambda$1(ContentActivity.java:67)

任何幫助表示贊賞。

編輯:

刪除並重新添加視圖確實可以,但是我認為這不是一個好的解決方案。

    view.setOnClickListener(v -> {
        final ArrayList<View> views = new ArrayList<>();
        for(int i = 0; i <= mRibbon.indexOfChild(view); i++) {
            views.add(mRibbon.getChildAt(i));
        }
        mRibbon.removeAllViews();
        for(View item : views) {
            mRibbon.addView(item);
        }

    });

嘗試這個:
1.使用子元素獲取對父元素的引用。
2.將父對象強制轉換為ViewGroup,以便您可以使用removeView方法。

((ViewGroup)scrollChildLayout.getParent()).removeView(scrollChildLayout);

而不是這樣:

//scrollView.removeView(scrollChildLayout);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM