Android не получает сенсорное событие в TextView с полосами прокрутки

У меня есть LinearLayout с некоторыми вложенными LinearLayouts, ImageView и TextViews. Один из TextView имеет полосы прокрутки. У меня есть переопределенный метод onTouchEvent() в моем классе LinearLayout, но когда вы касаетесь TextView полосой прокрутки, ничего не регистрируется.

Вот мой xml-файл (рассматриваемый TextView — последний элемент в этом макете):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:minWidth="310dp"
    android:layout_width="fill_parent">
    <LinearLayout
        android:id="@+id/from_linear_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="left">
        <ImageView
            android:src="@drawable/ic_dialog_info"
            android:id="@+id/notification_type_icon_image_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:scaleType="center"
            android:layout_margin="4dp"/>
            <TextView
                android:id="@+id/time_text_view"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:text="Timestamp"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:padding="1dp"
                android:textColorLink="?android:attr/textColorPrimaryDisableOnly"/>
    </LinearLayout>
    <ImageView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/under_contact_image_view"
        android:src="@drawable/divider_horizontal_dark"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="2dp"
        android:paddingTop="2dp" />
    <TextView
        android:text="Notification Text"
        android:id="@+id/notification_text_view"
        android:autoLink="all"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="?android:attr/textColorPrimaryDisableOnly"
        android:layout_width="fill_parent"
        android:gravity="left"
        android:paddingRight="10dp"
        android:paddingLeft="10dp"
        android:textColorLink="?android:attr/textColorPrimaryDisableOnly" 
        android:layout_gravity="left" 
        android:layout_height="70dip"
        android:scrollbars="vertical"/>
</LinearLayout>

Любые мысли по этому поводу, и если да, то кто-нибудь знает, как это преодолеть, чтобы я мог реализовать событие касания в этом TextView?


person Camille Sévigny    schedule 06.05.2011    source источник
comment
Что произойдет, если вы добавите android:focusable и android:clickable к LinearLayout?   -  person Joseph Earl    schedule 10.05.2011
comment
Разве вам не пришлось бы расширять LinearLayout, чтобы переопределить onTouchEvent? Если вы расширили класс, вам нужно поместить свой LinearLayout в XML вместо общего LinearLayout.   -  person Jim Clay    schedule 10.05.2011


Ответы (1)


Я ненавижу отвечать на свой вопрос, но я, наконец, понял этот. По сути, вы должны перехватывать сенсорные события, которые отправляются Activity. Затем в функции перехвата вы можете определить, какие события касания вы хотите обрабатывать и какие события вы хотите пропустить в действие и другие дочерние элементы.

Вот что у меня было, что позволило мне фиксировать события «пролистывания» или «броска», пропуская все другие события касания (например, он позволяет прокручивать вверх и вниз, длительное нажатие, события нажатия кнопки).

    MotionEvent _downMotionEvent;

/**
 * This function intercepts all the touch events.
 * In here we decide what to pass on to child items and what to handle ourselves.
 * 
 * @param motionEvent - The touch event that occured.
 */
@Override
public boolean dispatchTouchEvent(MotionEvent motionEvent){
    if (_debug) Log.v("NotificationActivity.dispatchTouchEvent()");
    NotificationViewFlipper notificationViewFlipper = getNotificationViewFlipper();
    switch (motionEvent.getAction()){
        case MotionEvent.ACTION_DOWN:{
            //Keep track of the starting down-event.
            _downMotionEvent = MotionEvent.obtain(motionEvent);
            break;
        }
        case MotionEvent.ACTION_UP:{
            //Consume if necessary and perform the fling / swipe action
            //if it has been determined to be a fling / swipe
            float deltaX = motionEvent.getX() - _downMotionEvent.getX();
            final ViewConfiguration viewConfiguration = ViewConfiguration.get(_context); 
            if(Math.abs(deltaX) > viewConfiguration.getScaledTouchSlop()*2){
                if (deltaX < 0){
                   //Do work here for right direction swipes.
                   return true;
                }else if (deltaX > 0){
                   //Do work here for left direction swipes.
                   return true;
                }
            }
            break;
        }
    }
    return super.dispatchTouchEvent(motionEvent);
}

Я надеюсь, что это поможет любому, кто столкнулся с подобной проблемой.

person Camille Sévigny    schedule 09.06.2011
comment
что использовать вместо устаревшего конструктора ViewConfiguration? - person topwik; 30.08.2012
comment
@Towpse - вы хотите сделать следующее (я также обновил ответ, чтобы отразить это): final ViewConfiguration viewConfiguration = ViewConfiguration.get(_context); - person Camille Sévigny; 31.08.2012