描述:
在一個ScrollView中,有一個固定了高度的 EditText,EditText 可以輸入很多文字,當文字過多時,需要滑動文字查看。此時,不能讓 ScrollView 滑動。同理,當觸摸到 EditText 以外的地方(ScrollView區域內)時,滑動界面的時候, EditText 內的文字,不能滑動。此外,如果EditText 中文字行數少,不用滑動,就可以看到全文的時候,在EditText中滑動,也是 界面進行滑動
解決思路:判斷EditText 中文字的行數,是否超過了能顯示的最大行數。如果超過了,就攔截事件,不讓父控件消費事件。
onInterceptTouchEvent(攔截事件),只在 ViewGroup中,纔會有
代碼:
MyEditTextLinearLayout
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;
import android.widget.LinearLayout;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
public class MyEditTextLinearLayout extends LinearLayout {
private static final String TAG = "ScrollviewEdit";
private NestedScrollView parentScrollview;
private EditText editText;
private int showLineMax = 0;
public MyEditTextLinearLayout(Context context) {
this(context,null);
}
public MyEditTextLinearLayout(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public MyEditTextLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setParentScrollview(NestedScrollView parentScrollview) {
this.parentScrollview = parentScrollview;
}
public void setEditeText(EditText editText) {
this.editText = editText;
LayoutParams lp = (LayoutParams) editText.getLayoutParams();
showLineMax = lp.height / editText.getLineHeight();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (parentScrollview == null) {
return super.onInterceptTouchEvent(ev);
} else {
if (ev.getAction() == MotionEvent.ACTION_DOWN && editText.getLineCount() >= showLineMax) {
// 將父scrollview的滾動事件攔截
setParentScrollAble(false);
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
// 把滾動事件恢復給父Scrollview
setParentScrollAble(true);
}
}
return super.onInterceptTouchEvent(ev);
}
/**
* 是否把滾動事件交給父scrollview
*
* @param flag
*/
private void setParentScrollAble(boolean flag) {
parentScrollview.requestDisallowInterceptTouchEvent(!flag);
}
}
佈局中使用
<ScrollView
android:id="@+id/myScrollView"
......>
<LinearLayout
......>
<...MyEditTextLinearLayout
android:id="@+id/myLl"
......>
<EditText
android:id="@+id/myEt"
......
......
/>
</...MyEditTextLinearLayout>
</LinearLayout>
</ScrollView>
界面代碼中使用
myLl.setParentScrollview(myScrollView);
myLl.setEditeText(myEt);