android - 首先在 child 的 parent 上调用 removeView()

标签 android scrollview

先介绍一点背景:

我在 ScrollView 中有一个布局。首先,当用户在屏幕上滚动时, ScrollView 会滚动。但是,经过一定量的滚动后,我要禁用 ScrollView 上的滚动,将“滚动焦点”移动到子布局内的 web View 上。这样,scrollview 会粘住,所有的滚动事件都会转到里面的 webview。

因此,对于一个解决方案,当达到滚动阈值时,我从 ScrollView 中删除子布局并将其放在 ScrollView 的父级中。(并使 ScrollView 不可见)。

// Remove the child view from the scroll view
scrollView.removeView(scrollChildLayout);

// Get scroll view out of the way
scrollView.setVisibility(View.GONE);

// Put the child view into scrollview's parent view
parentLayout.addView(scrollChildLayout);

总体思路:(-> 表示包含)

之前:父布局 -> ScrollView -> 滚动子布局

之后:parentLayout -> scrollChildLayout

上面的代码给了我这个异常:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
           at android.view.ViewGroup.addViewInner(ViewGroup.java:1976)
           at android.view.ViewGroup.addView(ViewGroup.java:1871)
           at android.view.ViewGroup.addView(ViewGroup.java:1828)
           at android.view.ViewGroup.addView(ViewGroup.java:1808)

你知道发生了什么吗?我显然是在父级上调用 removeView。

最佳答案

解决方案:

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

使用子元素获取对父元素的引用。将父级强制转换为 ViewGroup,以便您可以访问 removeView 方法并使用它。

感谢@Dongshengcn的解决方案

关于android - 首先在 child 的 parent 上调用 removeView(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6526874/

相关文章:

Android:如何在 AnimationDrawable 中获取当前帧

android - 应用程序启动时间过长

android - 使用 LinearLayoutManager 在 RecyclerView 中滚动到顶部

android - ImageView in LinearLayout in Scrollview with CardStackView and Picasso 图片不显示

swift - 编程式滚动 Apple TV 轻拂单元格

android - 如何在 Android kotlin 中使用 Google Analytics

android - 来自 BroadcastReceiver 的调用通知

android - 如何滚动背景图片?

android XML scrollview 和线性布局问题

android - ScrollView 和触摸监听器