- 最近接到一個(gè)需求,要在一個(gè)滾動(dòng)列表中有多個(gè)編輯框存在,而且有的編輯框高度固定袱贮,內(nèi)容可能顯示不下,需要上下滾動(dòng)來回查看体啰,然而最外層的父布局也是一個(gè)可以上下滾動(dòng)的布局攒巍,這明顯有沖突了。在查閱了相關(guān)博客以后荒勇,做出了一個(gè)完美的解決方式柒莉。
先放代碼
@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豎直方向是否可以滾動(dòng)
* @param editText 需要判斷的EditText
* @return true:可以滾動(dòng) false:不可以滾動(dòng)
*/
private boolean canVerticalScroll(EditText editText) {
//滾動(dòng)的距離
int scrollY = editText.getScrollY();
//控件內(nèi)容的總高度
int scrollRange = editText.getLayout().getHeight();
//控件實(shí)際顯示的高度
int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom();
//控件內(nèi)容總高度與實(shí)際顯示高度的差值
int scrollDifference = scrollRange - scrollExtent;
if(scrollDifference == 0) {
return false;
}
return (scrollY > 0) || (scrollY < scrollDifference - 1);
}
}
解析
首先我們需要在觸控到編輯框時(shí)將事件攔截下來交給編輯框自己處理,然后在滑動(dòng)時(shí)就會(huì)存在一個(gè)問題沽翔,編輯框是額定高度常柄,當(dāng)你滑動(dòng)的距離超出編輯框的區(qū)域的時(shí)候,這個(gè)時(shí)候就應(yīng)該講事件交給父布局處理,因?yàn)檫@個(gè)時(shí)候用戶明顯是想滑動(dòng)整個(gè)布局西潘,而不是編輯框卷玉。
參考博客:http://blog.csdn.net/z191726501/article/details/50701165