天天看點

聊天頁面彈出鍵盤資訊滾動到最後一條

效果圖:

聊天頁面彈出鍵盤資訊滾動到最後一條

實作原理:

· 給聊天資訊展示RecyclerView的根布局添加addOnLayoutChangeListener()監聽

代碼實作:

1、xml檔案裡的資訊展示布局如下:(代碼僅為頁面布局的資訊展示部分)
<FrameLayout
        android:id="@+id/fl_chat"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/ll_input"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_chat"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </FrameLayout>
           
2、在java代碼裡邊的監聽設定
//這裡flChat為聊天資訊展示RecyclerView所在的根布局
        FrameLayout flChat = (FrameLayout) findViewById(R.id.fl_chat);
        flChat.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) {

                if (bottom < oldBottom) {

                    //通過RecyclerView的滾動方法将聊天資訊滾動到最後一條
                    rvChat.scrollToPosition(adapterChat.getModels().size() - );
                }
            }
        });
           
3、如果要做到如QQ聊天翻動到中間的時候點選輸入框輸入内容不滾動最底部,可以給RecyclerView添加addOnScrollListener()監聽,判斷使用者主動滾動檢視中間資訊部分的話,增加一個boolean值判斷,在上部分(2)當中的onLayoutChange()方法判斷裡增加該boolean值條件。
That’s all, 日常項目當中碰到的小知識點,記錄下希望可以幫助到大家。Thank you!

繼續閱讀