【问题标题】:How to get the child of a SwipeRefreshLayout?如何获取 SwipeRefreshLayout 的子项?
【发布时间】:2021-03-13 18:32:28
【问题描述】:

我打算在给定的 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

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

【问题讨论】:

    标签: android swiperefreshlayout


    【解决方案1】:

    索引 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)
    

    【讨论】:

    • 如果添加Log.e(TAG, "onCreate: "+swipeRefreshLayout.getChildAt(i) );,您会注意到 swipeRefreshLayout 由 2 个视图组成,第一个是您在滑动 swipeRefreshLayout 时看到的 progressView(CircleImageView),第二个视图是您的 WebView
    • 这个也可以:(WebView) swipeRefreshLayout.getChildAt(1);
    • 是的,我使用循环来更清晰,因为它包含多个视图
    • 你的回答更准确。 Tnx 伴侣!
    • 我认为对于一个视图不会改变孩子的数量,你可以像 swipRef 一样直接使用 getChildAt(1)。但是对于可以动态更改子节点数量的 ViewGroup,最安全的方法是使用 for 循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多