Reputation: 424
I am trying to achieve a specific keyboard behaviour in a sample chat app in which when user opens keyboard the RecyclerView
goes up with the keyboard but only if the last chat visible is visible.
Example: In WhatsApp
open keyboard when last message is visible, the list will go up with the keyboard in order to stay visible to the user. Now scroll up a little and then open keyboard, now the list will stay as it is and it won't go up with the keyboard.
Upvotes: 1
Views: 1077
Reputation: 241
Just add
android:windowSoftInputMode = "adjustResize"
inside your activity tag in the manifest.
Upvotes: 0
Reputation: 281
You can directly add windowSoftInputMode in your Manifest file inside the activity tag like this :-
<activity android:name=".ui.chat.ChatActivity"
android:windowSoftInputMode="adjustResize|stateAlwaysHidden"/>
If any query,you can ask.
Upvotes: 1
Reputation: 424
For achieving the behaviour of scrolling the list upside along with keyboard, I derived the solution from here: https://stackoverflow.com/a/34103263/1739882
And to add custom behaviour that decides whether to scroll the list or not I fetched the last visible item with this:
linearLayoutManager.findLastVisibleItemPosition()
and used a flag to handle the scenario. Here is the complete code:
//Setup editText behavior for opening soft keyboard
activityChatHeadBinding.edtMsg.setOnTouchListener((v, event) -> {
InputMethodManager keyboard = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (keyboard != null) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) activityChatHeadBinding.recyclerView.getLayoutManager();
isScrollToLastRequired = linearLayoutManager.findLastVisibleItemPosition() == chatNewAdapter.getItemCount() - 1;
keyboard.showSoftInput(findViewById(R.id.layout_send_msg), InputMethodManager.SHOW_FORCED);
}
return false;
});
//Executes recycler view scroll if required.
activityChatHeadBinding.recyclerView.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
if (bottom < oldBottom && isScrollToLastRequired) {
activityChatHeadBinding.recyclerView.postDelayed(() -> activityChatHeadBinding.recyclerView.scrollToPosition(
activityChatHeadBinding.recyclerView.getAdapter().getItemCount() - 1), 100);
}
});
Upvotes: 2