首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 判斷 ScrollView 是否已存在於容器中

     編輯:程式設計綜合問答

問題

動態添加 ScrollView 到 LinearLayout,需防止重複添加。如何檢查容器中是否已存在 ScrollView?

解決方案:遍歷子視圖檢查型別

public void tickBox(int i) {
    LinearLayout mainView = findViewById(R.id.MainLayout);
    ScrollView sc = new ScrollView(this);
    sc.setId(i + 100);

    // 檢查是否已存在 ScrollView
    boolean hasScrollView = false;
    for (int j = 0; j < mainView.getChildCount(); j++) {
        View child = mainView.getChildAt(j);
        if (child instanceof ScrollView) {
            hasScrollView = true;
            break;
        }
    }

    if (!hasScrollView) {
        mainView.addView(sc);
    }
    // 其他邏輯...
}

進階封裝:通用工具方法

public static <T extends View> boolean hasViewOfType(ViewGroup container, Class<T> clazz) {
    for (int i = 0; i < container.getChildCount(); i++) {
        if (clazz.isInstance(container.getChildAt(i))) {
            return true;
        }
    }
    return false;
}

// 使用
if (!hasViewOfType(mainView, ScrollView.class)) {
    mainView.addView(sc);
}

替代方案:ID 追蹤

若每次創建的 ScrollView 設置固定 ID:

private static final int SCROLL_VIEW_ID = 0x7F080001; // 自定義 ID 範圍

// 添加前檢查
if (mainView.findViewById(SCROLL_VIEW_ID) == null) {
    ScrollView sc = new ScrollView(this);
    sc.setId(SCROLL_VIEW_ID);
    mainView.addView(sc);
}

最佳實踐建議

  • 優先使用 XML 靜態佈局:<ScrollView> 直接寫在布局中,android:visibility="gone" 控制顯隱,避免動態創建開銷
  • 動態場景用 Tag 標記:sc.setTag("dynamic_scroll"),查找時 mainView.findViewWithTag("dynamic_scroll")
  • 考慮 NestedScrollView:支援嵌套滾動,協同 CoordinatorLayout 更佳
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved