2016年5月18日 星期三

讓scrollview不能捲動的三種方法



方法一
推薦此種方法
public class BlockScrollView extends ScrollView {
    //private boolean shouldWindowFocusWait;

    public BlockScrollView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public BlockScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BlockScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    // true if we can scroll (not locked)
    // false if we cannot scroll (locked)
    private boolean mScrollable = true;

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

    public boolean isScrollable() {
        return mScrollable;
    }

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

}



方法二
但此一方法,會使scrollview裡面的元件(例如textview),也不能動作(fling,swipe,click等...)
        scrollView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            return isBlockedScrollView;
        }
    });





方法三
如果scrollview裡面有textview有時會出現一些奇怪現象(畫面顯示不全,空白等)
import android.content.Context;
import android.text.Selection;
import android.text.Spannable;
import android.util.AttributeSet;
import android.widget.TextView;

public class BlockScrollView extends ScrollView {
    //private boolean shouldWindowFocusWait;
    public boolean isScroll =true;

    public BlockScrollView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public BlockScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BlockScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void scrollTo(int x, int y) {
        if (isScroll) {
            super.scrollTo(x,y);
        }
        //do nothing
    }
}


  © Blogger templates Psi by Ourblogtemplates.com 2008

Back to TOP