![](/img/trans.png)
[英]Keep the scroll position of a list while adding item to the top in Android
[英]Android keep scroll position and text in chat app
我正在開發一個Android聊天應用程序,並且有一個屏幕,其中包含要聊天的所有聊天成員的列表(RecyclerView)。 當我單擊一個成員時,會出現另一個屏幕,其中包含該選定成員的所有消息的列表(RecyclerView)。
當我切換到另一個成員時,如何實現保持消息滾動列表的位置並保存撰寫的文本(以防消息尚未發送)? 返回特定列表時,我想恢復這些設置。
這是您要做的。 首先,我假設您擁有一個活動,該活動可以監視應用程序中的所有聊天並顯示它們。 如您所說,每個聊天的ID與另一個聊天的ID不同。 如果這些假設與您的應用程序的性質不符,請發表評論,以便我編輯答案!
我提供的解決方案速度很快,即使您關閉了電話,您仍可以找回位置(“回收者視圖”)和聊天文本(在編輯文本中),您仍然可以恢復這些值。
有三種方法可以在活動類中定義它們:第一種是:
private boolean setChatScrollPositionAndText(String chat_text,int position,String chat_id){
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(chat_id+"position",position);
editor.putString(chat_id+"text",chat_text);
return editor.commit();
}
第二和第三是:
private String getLastText(String chat_id){
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
return sharedPref.getString(chat_id+"text","");
}
private int getLastPosition(String chat_id){
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
return sharedPref.getInt(chat_id+"position",0);
}
第一個方法將接受三件事chat_text
, position
和chat_id
所有這些值都可以從布局視圖中獲取。 暫停活動時,應在活動onPause
方法中調用此方法,以將其保存為:
@Override
protected void onPause() {
super.onPause();
setChatScrollPositionAndText("your chat text from edit text",0,"your unique chat id");
}
您可以從editText
獲得這些值以從聊天文本中傳遞,其中editText
的使用類型和position
來自recyclerView
的適配器或布局管理器,還可以傳遞chat的id作為第三個參數將其保存在那里,因為它們被保存了。
然后,要檢索所有這些值,就必須在活動的onResume
方法中對其進行調用,即使剛剛恢復活動也是如此
@Override
protected void onResume() {
super.onResume();
String myTextWas=getLastText("your unique chat id");
int my_recycler_position=getLastPosition("my unique chat id");
}
要進行檢索,您將使用第二種方法和第三種方法,采用此值並將其用於在編輯文本中設置文本和/或將recyclerView滾動到所獲得的位置。
注意:如果這是用戶第一次訪問聊天,則默認位置為0
,默認字符串為""
空字符串。 整個解決方案使用SharedPreferences,這是將鍵值對保存在android中的方法。您可以進行自我訓練並從android官方培訓中獲得更多解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.