ScrollView中使用EditText,并解决滑动冲突

描述:
在一个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);
发布了114 篇原创文章 · 获赞 33 · 访问量 22万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章