使用步骤
- xml 布局文件布局,和普通的控件一下
- 获取SoftInputCanListenerEditText 实例,并设置监听器
- Activity 注册的时候android:windowSoftInputMode 使用默认值,就是说不要写这个就对了
/**
* author: vector.huang
* date: 2016/10/12 19:07
*/
public class SoftInputCanListenerEditText extends AppCompatEditText {
private OnSoftInputChangeListener mOnSoftInputChangeListener;
private int mPreHeight; //上一次计算时的高度
private View mContentView;
private boolean isShow;
public SoftInputCanListenerEditText(Context context) {
super(context);
}
public SoftInputCanListenerEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SoftInputCanListenerEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setOnSoftInputChangeListener(OnSoftInputChangeListener onSoftInputChangeListener) {
mOnSoftInputChangeListener = onSoftInputChangeListener;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode()) {
return;
}
if (mContentView == null) {
Activity activity = (Activity) ((TintContextWrapper) getContext()).getBaseContext();
mContentView = activity.findViewById(android.R.id.content);
}
int nowHeight = mContentView.getHeight();
if (mPreHeight == 0) {
//第一次进入
mPreHeight = nowHeight;
return;
}
if (mPreHeight == nowHeight) {
//同样的不处理
return;
}
if (mOnSoftInputChangeListener != null && nowHeight < mPreHeight) {
//变小了之后就是显示了键盘
mOnSoftInputChangeListener.onChange(true);
isShow = true;
//显示键盘之后就开始检查什么时候收起
startCheck();
mPreHeight = nowHeight;
}
}
private Runnable check = () -> {
int nowHeight = mContentView.getHeight();
if (mOnSoftInputChangeListener != null && nowHeight > mPreHeight) {
//变小了之后就是显示了键盘
mOnSoftInputChangeListener.onChange(false);
isShow = false;
mPreHeight = nowHeight;
return;
}
//键盘没有收起,接着检查
startCheck();
};
//定时检查才行呀
private void startCheck() {
postDelayed(check, 100);
}
public boolean isShow() {
return isShow;
}
public interface OnSoftInputChangeListener{
void onChange(boolean isShow);
}
}
感谢支持,更多请看把时间当初朋友
网友评论