EditText嵌套在ScrollView中的滑动冲突问题解决

在某些场景下,需要使用EditText来让用户输入信息。当EditText设置maxLines后,用户输入行数超过maxLines后,只能通过上下滑动来浏览所有文字。

但当EditText外层使用ScrollView来让整个界面滑动时,用户触摸EditText区域时不能再显示折叠的文字,而只是滑动了整个srollview。

实现时需要注意的是,当EditText框内容并未超过maxLines时,此时用户触摸EditText区域进行滑动时,期望整个ScrollView是滑动的;只有当EditText框内容大于maxLines时,才需要由EditText自身来处理滚动事件。

具体解决方案如下:

//设置touch事件
mEditText = (EditText) findViewById(R.id.edit_text);
mEditText.setOnTouchListener(this);

//重写onTouch方法
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
        //触摸的是EditText控件,且当前EditText可以滚动,则将事件交给EditText处理;否则将事件交由其父类处理
        if ((view.getId() == R.id.edit_text && canVerticalScroll(mEditText))) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return false;
}

/**
* EditText竖直方向是否可以滚动
* @param editText  需要判断的EditText
* @return  true:可以滚动   false:不可以滚动
*/
private boolean canVerticalScroll(EditText editText) {
        if(editText.canScrollVertically(-1) || editText.canScrollVertically(1)) {
            //垂直方向上可以滚动
            return true;
        }
        return false;
}

canScrollVertically的源码说明及实现如下:

    /**
     * Check if this view can be scrolled vertically in a certain direction.
     *
     * @param direction Negative to check scrolling up, positive to check scrolling down.
     * @return true if this view can be scrolled in the specified direction, false otherwise.
     */
    public boolean canScrollVertically(int direction) {
        final int offset = computeVerticalScrollOffset();
        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
        if (range == 0) return false;
        if (direction < 0) {
            return offset > 0;
        } else {
            return offset < range - 1;
        }
    }

该函数要求sdk的版本是API14及以上。如果需要兼容4.0以下版本,可参考源码中computeVerticalScrollOffset、computeVerticalScrollRange、computeVerticalScrollExtent的实现。注意子类可能重写View中的该方法。

    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

你可能感兴趣的:(EditText嵌套在ScrollView中的滑动冲突问题解决)