簡體   English   中英

出現軟鍵盤時如何向上推 RecyclerView?

[英]How to push RecyclerView up when the soft keyboard appears?

我想建立一個像 WhatsApp 這樣的消息布局。 我有一個EditText和一個RecyclerView

問題是當鍵盤出現時,它會隱藏列表底部的消息。

所以讓我們說這個RecyclerView

---item 1---  
---item 2---  
---item 3---  
---item 4---  
---EditText---

當鍵盤出現時,我得到了這個:

---item 1---  
---item 2---  
---EditText---
---Keyboard---  

但我想得到這個:

---item 3---  
---item 4---  
---EditText---
---Keyboard---

注意:當我設置linearLayoutManager.setStackFromEnd(true); 它可以工作,但是當有一條消息時,它會出現在頁面底部。

使用 recyclerview 和 editText 為活動設置 adjustresize :

android:windowSoftInputMode="adjustResize"

將 onLayoutChangeListener 添加到 RecyclerView 並在 onLayoutChange 中將 scrollToPosition 設置為 data.size() -1:

  mRecyclerView.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)
{

mRecyclerView.scrollToPosition(mMessages.size()-1);

}
    });

我這樣做的方式是根據item holder的大小設置setStackFromEnd(),並在androidManifest中設置adjustResize。

這就是我檢查的方式:

if (recycleView.getChildCount() == items.size()){
    mLayoutManager.setStackFromEnd(true);
}
else{
    mLayoutManager.setStackFromEnd(false);
}

我不擅長英語。 使用 ChatRecyclerView 並將線性布局管理器的 stackfromend 設置為 false。

public class ChatRecyclerView extends RecyclerView {
    private int oldHeight;

    public ChatRecyclerView(Context context) {
        super(context);
    }

    public ChatRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ChatRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        int delta = b - t - this.oldHeight;
        this.oldHeight = b - t;
        if (delta < 0) {
            this.scrollBy(0, -delta);
        }
    }
}

感謝 Kotlin 中的devdoot Ghosh (我檢查適配器大小是否 > 0):

recycler_view.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
    // Wait till recycler_view will update itself and then scroll to the end.
    recycler_view.post {
        adapter?.itemCount?.takeIf { it > 0 }?.let {
            scrollToPosition(it - 1)
        }
    }
}

AndroidManifest中添加到活動:

<activity
    ...
    android:windowSoftInputMode="adjustResize"
    />

請注意, RecyclerView將滾動到最后一項。

單擊編輯文本時,我從推送內容中獲得了解決方案

只需將以下代碼放入

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM