【Android】解决ScrollView中嵌套EditText时的滑动滚动冲突

版权声明:转载请标明本博客地址: https://blog.csdn.net/xiaodouyaer624/article/details/79158300

仅供个人参考使用,如果你喜欢,你也可以用。保护网络环境,拒绝喷子。我是无私奉献的,没让喷子拿一分钱,喷子请闭嘴。

0、二话不说,上工具类代码

import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

/**
 * 用于解决EditText和ScrollView的触摸滚动冲突
 * Created by LiuChaoya on 2018/1/25 09:46.
 * email  [email protected]
 */

public class SolveEditTextScrollClash implements View.OnTouchListener {

    private EditText editText;

    public SolveEditTextScrollClash(EditText editText) {
        this.editText = editText;
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        //触摸的是EditText而且当前EditText能够滚动则将事件交给EditText处理。否则将事件交由其父类处理
        if ((view.getId() == editText.getId() && canVerticalScroll(editText))) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            if (event.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return false;
    }

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

1、在需要处理冲突的类中直接调用,举个栗子

EditText editText = (EditText)findViewById(R.id.editText);
editText.setOnTouchListener(new SolveEditTextScrollClash(editText));

2、结束(代码很少,不提供下载链接,请需要的自行copy)。

猜你喜欢

转载自blog.csdn.net/xiaodouyaer624/article/details/79158300