動態添加 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);
}
若每次創建的 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);
}
<ScrollView> 直接寫在布局中,android:visibility="gone" 控制顯隱,避免動態創建開銷sc.setTag("dynamic_scroll"),查找時 mainView.findViewWithTag("dynamic_scroll")