最近在做一個客服聊天項目卵蛉,使用recyclerview做聊天列表娘纷,但是遇到了一個無法處理的問題,這問題困了我半天狗准,也是醉了克锣,之前使用listview沒有遇到這樣的,對于鍵盤的各種嘗試都嘗試了腔长,最后還是沒有解決袭祟,先來看看我已開始常規(guī)的搬磚:
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/message_recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="vertical"/>
<LinearLayout
android:id="@+id/bottom_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center_vertical"
android:orientation="horizontal">
<EditText
android:id="@+id/message_et"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="請輸入發(fā)送的信息"
android:imeActionId="@+id/send"
android:imeOptions="actionSend"
android:inputType="text"
android:maxLines="1"
android:singleLine="true"/>
<ImageButton
android:id="@+id/send_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_menu_send"/>
</LinearLayout>
</LinearLayout>
沒咋可說的,中規(guī)中矩捞附,接下來在AndroidManifest.xml配置:
<activity
android:name=".chat.ChatActivity"
android:parentActivityName=".activity.MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize|stateHidden"
ools:targetApi="jelly_bean">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activity.MainActivity"/>
</activity>
可以看到android:windowSoftInputMode="adjustResize|stateHidden"設(shè)置了巾乳,理論上這樣就沒有問題了,然而實際上并沒有什么效果鸟召,這個不行胆绊,那就試試另外一個吧,android:windowSoftInputMode="adjustPan|stateHidden"欧募,這個是能把布局彈上去了压状,但是但是TM的標(biāo)題一彈上去了,也就是整體布局都彈上去跟继,后來各種折騰种冬,也沒有效果,網(wǎng)上各種找也沒用舔糖,最后冷靜下來思考娱两,不對啊,我該設(shè)置的都設(shè)置的啊金吗,跟之前有什么不一樣呢十兢?想想除了RecyclerView,其他沒有什么不一樣了辽聊,最后決定從Recyclerview入手纪挎,果然后面找到了,在設(shè)置setLayoutManager的是要先調(diào)用如下代碼才有效
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true); //鍵盤彈出
mRecyclerView.setLayoutManager(layoutManager);
就是調(diào)用setStackFromEnd跟匆,設(shè)置為true异袄,這樣就可以將布局跟著輸入框彈上去了,而且標(biāo)題沒有被彈出去玛臂,而這個方法本身的意思是始終保持最新添加的item顯示在recyclerview上烤蜕,可以看下他的源碼:
public void setStackFromEnd(boolean stackFromEnd) {
assertNotInLayoutOrScroll(null);
if (mStackFromEnd == stackFromEnd) {
return;
}
mStackFromEnd = stackFromEnd;
requestLayout();--->mRecyclerView.requestLayout();
}
可以看到布局會被重新調(diào)整封孙。
最后附上效果圖:
聊天列表.png