参考:
完美解决EditText和ScrollView的滚动冲突(上)
完美解决EditText和ScrollView的滚动冲突(下)
EditText输入框的内容超过高度或最大行数就可垂直滚动
定义最大行数:
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/rectangle_shape"
android:gravity="top"
android:hint="输入框"
android:maxLines="3"
android:minLines="3" />
定义固定高度:
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@drawable/rectangle_shape"
android:gravity="top"
android:hint="输入框" />
当EditText处于ScrollView中时,
1、内容超过高度或最大行数EditText不能滚动,部分内容看不到。
2、内容没超过高度或最大行数EditText时,要随ScrollView一起滚动。
解决示例:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="300dp"
android:gravity="center"
android:text="Hello World Begin!" />
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@drawable/rectangle_shape"
android:gravity="top"
android:hint="输入框" />
<TextView
android:layout_width="match_parent"
android:layout_height="300dp"
android:gravity="center"
android:text="Hello World End!" />
</LinearLayout>
</ScrollView>
/**
* 监听软键盘,在软键盘关闭时显示其他
*/
public class MainActivityI extends AppCompatActivity implements View.OnTouchListener {
private EditText mEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maini);
mEditText = (EditText) findViewById(R.id.edit_text);
mEditText.setOnTouchListener(this);
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
//触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理;否则将事件交由其父类处理
if ((view.getId() == R.id.edit_text && canVerticalScroll(mEditText))) {
view.getParent().requestDisallowInterceptTouchEvent(true);//告诉父view,我的事件自己处理
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
view.getParent().requestDisallowInterceptTouchEvent(false);//告诉父view,你可以处理了
}
}
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);
}
}