1. 程式人生 > >Android RecyclerView內容被鍵盤遮擋問題

Android RecyclerView內容被鍵盤遮擋問題

原文地址:https://blog.csdn.net/qq_16782391/article/details/71123824


      做過IM介面開發者可能會遇到,當輸入框獲取焦點recyclerview的內容會被鍵盤遮擋,無法像微信一樣將列表訊息定位到最後一個,嚴重影響使用者體驗,現在將我遇到的問題和解決方案記錄下來:

一.在搜尋一些資料時,出現以下的解決方案,缺陷我記錄下來

在AndroidManifest的Activity中設定軟鍵盤屬性

android:windowSoftInputMode="adjustResize"

//需要在佈局管理器中設定setStackFromEnd(true),程式碼如下:

LinearLayoutManager mManager =newLinearLayoutManager(mContext);mManager.setStackFromEnd(true);//關鍵recyclerView.setLayoutManager(mManager);

使用上述方法,當item數量佔滿整個螢幕時,這種方式可以解決問題,但是當item專案很少時,會出現item自動定位到底部的問題,效果圖如下:


二.解決方案如下:

我們可以監聽軟鍵盤的改變,使用recyclerview.addOnLayoutChangeListener(),如果bottom小於oldBottom,說明鍵盤是彈起。

	chatList.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {//
			
			@Override
			public void onLayoutChange(View v, int left, int top, int right,
					int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
				// TODO Auto-generated method stub
				
				if (bottom < oldBottom) {
					chatList.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							chatList.scrollToPosition(chatAdapter.getAllData().size() -1);
						}
					},100);
				}
			}
		});

這樣item數目少的時候顯示正常,鍵盤彈出時自動定位到最後一個item,解決了內容遮擋的問題。