開門見山!如果EditText內容過長,但控件高度有限的時候,在滑動內容的時候就會有滑動衝突了,處理方式是要先判斷EditText內容是否過長,即可滾動時,設置父容器(即ScrollView)分發事件爲關閉狀態,否則爲打開狀態。附上相關代碼:
判斷EditText內容是否過長可滾動:
public static 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叫testEditText:
testEditText.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //觸摸的是EditText並且當前EditText可以滾動則將事件交給EditText處理;否則將事件交由其父類處理 if ((v == testEditText && canVerticalScroll(testEditText))) { v.getParent().requestDisallowInterceptTouchEvent(true); if (event.getAction() == MotionEvent.ACTION_UP) { v.getParent().requestDisallowInterceptTouchEvent(false); } } return false; } });