簡體   English   中英

以編程方式獲取ScrollView的子級

[英]Get child of ScrollView programmatically

我制作了一個自定義ScrollView ,其中有一個孩子(布局)。 使用CustomScrollView.java findViewByid通過ID查找子項會導致應用程序崩潰,因此可以通過類似於this (檢測到自定義scrollview)或getParent() (檢測到父布局getParent()的簡單方式找到它滾動視圖和孩子都在里面嗎?

我正在嘗試應用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>

我要在其中添加requestDisallowInterceptTouchEvent CustomScrollView.java內部的代碼:

    @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訪問子視圖(嵌套的視圖深於當前視圖)。 由於requestDisallowInterceptTouchEvent僅適用於ViewGroup,因此您必須將其直接強制轉換為ConstraintLayout或(為了更好的可重用性)強制轉換為ViewGroup。

請注意,如果孩子有空,我還沒有提供任何檢查。

對於Kotlin和Java,此代碼也相同。 它沒有任何區別(從語法上是可以的,但是概念是相同的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM