关于NestedScrollView或者ScrollView布局中嵌套EditText的滑动冲突

  • 最近接到一个需求,要在一个滚动列表中有多个编辑框存在,而且有的编辑框高度固定,内容可能显示不下,需要上下滚动来回查看,然而最外层的父布局也是一个可以上下滚动的布局,这明显有冲突了。在查阅了相关博客以后,做出了一个完美的解决方式。
先放代码
@SuppressLint("AppCompatCustomView") public class PLEditText extends EditText {

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

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

  public PLEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }


  @Override public boolean onTouchEvent(MotionEvent event) {
    int oldy = (int) event.getY();
    final int action = event.getActionMasked();
    if (action == MotionEvent.ACTION_DOWN) {
      getParent().requestDisallowInterceptTouchEvent(true);
    } else if (action == MotionEvent.ACTION_MOVE) {
      if (canVerticalScroll(this)) {
        getParent().requestDisallowInterceptTouchEvent(true);
      }else {
        getParent().requestDisallowInterceptTouchEvent(false);
      }
    } else if (action == MotionEvent.ACTION_UP) {
      getParent().requestDisallowInterceptTouchEvent(false);
    }
    return super.onTouchEvent(event);
  }

  /**
   * EditText竖直方向是否可以滚动
   * @param editText  需要判断的EditText
   * @return  true:可以滚动   false:不可以滚动
   */
  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);
  }
}
解析

首先我们需要在触控到编辑框时将事件拦截下来交给编辑框自己处理,然后在滑动时就会存在一个问题,编辑框是额定高度,当你滑动的距离超出编辑框的区域的时候,这个时候就应该讲事件交给父布局处理,因为这个时候用户明显是想滑动整个布局,而不是编辑框。

参考博客:http://blog.csdn.net/z191726501/article/details/50701165

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,744评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,303评论 4 61
  • 如果到了春天 我还不能好好(迅速)走到田野中去 那么春天是不存在的春天 那么美好是荒芜的美好 我以为这很简单,结果...
    咛初阅读 427评论 1 8
  • 互联网的理念是高速、大范围的传播,而有效传播的前提是,能精确地找到有效的受众。当然,最重要的是,传播的“物”一定是...
    bybateer阅读 445评论 0 0