在Android电视上禁用滚动视图

问题描述 投票:0回答:1

如何创建具有不可滚动滚动视图的自定义类?我试过了:

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);
    }


}

但是我仍然可以滚动。

该类似乎仅在触摸设备上有效,在android电视上,我使用方向键。

如何修改此类以在android电视上工作?我需要只能以编程方式滚动,而不能使用键盘滚动。谢谢

android scrollview android-tv
1个回答
0
投票

您可以使用ScrollView的dispatchKeyEvent回调-

@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;
}

基本上是一样的,但是有键盘事件而不是触摸。

一旦不希望发生超级方法,请返回true。>>

© www.soinside.com 2019 - 2024. All rights reserved.