我制作了一个自定义的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/