Search code examples
androidscrollviewandroid-tv

Disable scrollview on Android tv


how can I create a custom class with a non scrollable scrollview? I tried this:

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.ScrollView;

public class DisabledScrollView extends ScrollView {

    // true if we can scroll (not locked)
    // false if we cannot scroll (locked)
    private boolean mScrollable = false;

    public DisabledScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }
    public DisabledScrollView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public DisabledScrollView(Context context)
    {
        super(context);
    }

    public void setScrollingEnabled(boolean enabled) {
        mScrollable = enabled;
    }

    public boolean isScrollable() {
        return mScrollable;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        return false ;
    }
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        return false ;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // if we can scroll pass the event to the superclass
                if (mScrollable) return super.onTouchEvent(ev);
                // only continue to handle the touch event if scrolling enabled
                return mScrollable; // mScrollable is always false at this point
            default:
                return super.onTouchEvent(ev);
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // Don't do anything with intercepted touch events if
        // we are not scrollable
        if (!mScrollable) return false;
        else return super.onInterceptTouchEvent(ev);
    }


}

however I'm still able to scroll.

This class seems to only work on touch devices, with android tv I use the directional key.

How can I modify this class to work on android tv? I need to be able to scroll only programmatically and not with the pad. Thanks


Solution

  • You can use ScrollView's dispatchKeyEvent callback -

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
    
        if (event.getAction() == KeyEvent.ACTION_UP) {
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    if (mScrollable) {
                        return super.dispatchKeyEvent(event);
                    }
                    break;
            }
        }
        return true;
    }
    

    Basically does the same but with Dpad events instead of touch.

    Return true once you've handled the event.