java - 以编程方式获取 ScrollView 的子级

标签 java android android-scrollview

我制作了一个自定义的ScrollView,其中有一个子项(布局)。在 CustomScrollView.java 中使用 findViewByid 通过 ID 查找子项会导致应用程序崩溃,那么是否可以通过类似于 this< 的简单方式找到它 (检测自定义 ScrollView )或 getParent() (检测 ScrollView 和 subview 所在的父布局)?

我正在尝试将 requestDisallowInterceptTouchEvent(true); 应用到自定义 ScrollView 的子级。

xml:

<?xml version="1.0" encoding="utf-8"?>

<com.example.test4.CustomScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/dynamic_status_scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none"
    tools:context=".MainActivity">

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/dynamic_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:context=".MainActivity">
    </android.support.constraint.ConstraintLayout>

</com.example.test4.CustomScrollView>

CustomScrollView.java 内的代码,我想在其中添加 requestDisallowInterceptTouchEvent:

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Add here
        return super.onTouchEvent(ev);
    }

问题:

简而言之,我想找到自定义 ScrollView 的子级,即 id 为 dynamic_status 的布局,而不使用 findViewById

最佳答案

你应该能够这样做:

@Override
public boolean onTouchEvent(MotionEvent ev) {
    ((ConstraintLayout)getChildAt(0)).requestDisallowInterceptTouchEvent(true);
    return super.onTouchEvent(ev);
}

您始终可以使用 getChildAt 访问 subview (比当前 View 嵌套更深的 View )。由于 requestDisallowInterceptTouchEvent 仅适用于 ViewGroup,因此您必须将其直接转换为 ConstraintLayout,或者为了获得更好的可重用性,将其转换为 ViewGroup。

请注意,我没有包含任何检查 child 是否有空。

此代码对于 Kotlin 和 Java 也是相同的。它没有任何区别(语法上是的,但概念是相同的)。

关于java - 以编程方式获取 ScrollView 的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54037654/

相关文章:

java - 适用于 Android Java 的嵌套查询 Firebase Firestore

android - 如何以编程方式在 NestedScrollView 中显示滚动条。

java - 如何将 UTF-8 字节 block 转换为字符?

java - 使用 Guice 注入(inject)通用实现

android - 在 MvvmCross 3.5.1 中实现 fragment 的正确方法是什么

android - 将 View 添加到 ScrollView,然后滚动到底部 : Which callback is needed?

Android NestedScrollView 在 CoordinatorLayout 中平滑滚动

java - 为什么 System 类声明为 final 并带有私有(private)构造函数?

java - 如何更改 servlet 将 PDF 流式传输到的浏览器页面的标题?

android - 如何在 Recyclerview 不可见时禁用 RecyclerView 适配器