如何获得 SwipeRefreshLayout 的孩子?

问题描述

我打算在给定的 SwipeRefreshLayout 中获取 WebView 子项。孩子是通过 addView() 方法添加的:

swipeRefreshLayout.addView(webView);

这应该很简单。由于我必须取回 webview,因此我必须将其强制转换:

(WebView) swipeRefreshLayout.getChildAt(0);

然而,这给了我一个例外。

java.lang.classCastException: b.t.b.a cannot be cast to android.webkit.WebView

我也尝试将布局转换为 ViewGroup,但 android studio 提到它是多余的。

解决方法

索引 0 处的子项是 CircleImageView,第二个子项是您在 xml 文件中添加到其中的 View。请尝试:

  int childCount = swipeRefreshLayout.getChildCount();
        WebView webView;
        for (int i =0 ;i<childCount;i++){ 
            if (swipeRefreshLayout.getChildAt(i) instanceof  WebView){
                webView = (WebView) swipeRefreshLayout.getChildAt(i);
            }
        }

 // here you can use your WebView

或者你可以直接使用

swipeRefreshLayout.getChildAt(1)