步骤:
1.AndroidManifest配置
<activity
android:name=".xxactivity"
android:configChanges="orientation|keyboardHidden"
android:windowSoftInputMode="adjustResize"></activity>
2.获取view在屏幕中的Y值
public int getY(View view) {
//获取点击评论的item的位置
int[] location = new int[2];
view.getLocationOnScreen(location);
return location[1];
}
3.控制软件盘显示与隐藏
//判断软键盘是否存在
public static boolean isSoftShowing(Activity context) {
//获取当前屏幕内容的高度
int screenHeight = context.getWindow().getDecorView().getHeight();
//获取View可见区域的bottom
Rect rect = new Rect();
context.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
return screenHeight - rect.bottom > 150;
}
//显示软键盘
public static void showSoftInput(Context context, View view) {
if (context != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
//强制隐藏键盘
public static void hideSoftInput(Context context, View view) {
if (context != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
4.输入框到指定位置
/**
* 显示输入框的位置
*
* @param commentView 点击 view
*/
@Override
public void showInputComment(View commentView) {
// 输入框要显示指定view的Y轴位置
final int rvInputShowY = getY(commentView);
//显示指定view的高
final int rvInputShowHeight = commentView.getHeight();
//软键盘是否显示,不显示则弹出
if (!TextUtil.isSoftShowing(this)) {
TextUtil.showSoftInput(this, etCommentReplay);
//输入框EditText获取焦点
etCommentReplay.requestFocus();
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//输入框view的Y轴位置,layoutBottomView为输入框View
int InputViewY = getY(layoutBottomView);
//RecyclerView 滚动到指定位置
list.smoothScrollBy(0, rvInputShowY - (InputViewY - rvInputShowHeight));
}
}, 300);
}
5.列表滚动监听,隐藏软键盘
//RecyclerView
list.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//判断是否手动拖拽滑动
if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
if (TextUtil.isSoftShowing(XXAcitvity.this)) {
TextUtil.hideSoftInput(XXAcitvity.this, etCommentReplay);
}
}
}
});