您可能會setSelectionFromTop()
並通過自定義列表視圖重寫onSizeChanged()
實現這個滾動。在你的佈局中,你應該有一個RelativeLayout
有一個父容器,並將該列表視圖放在edittext上方。
通過創建自己的列表視圖並覆蓋onSizeChange()
,您將能夠在listview調整大小並獲取其新高度之前獲取最後一個可見項目的位置,以最終設置列表的「上一個」位置與偏移量的高度。
工作原理:您的列表將把上一個最後一個可見項放置在其頂部,您將添加像素以將其滾動到底部,即在edittext上方。
要覆蓋的方法,並與偏移顯示,執行如下:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// get last visible item's position before resizing
int lastPosition = super.getLastVisiblePosition();
// call the super method to resize the listview
super.onSizeChanged(w, h, oldw, oldh);
// after resizing, show the last visible item at the bottom of new listview's height
super.setSelectionFromTop(lastPosition, (h - lastItemHeight));
}
lastItemHeight
是一點點的解決辦法,因爲我沒有找到如何在這之前onSizeChanged被稱爲得到最後一個項目的高度。然後,在listview包含許多類型的項目(沒有相同高度)的情況下,我更願意在發生事件時(即在SoftKeyboard打開之前)獲取選定的高度。
所以在自定義列表視圖,你有這樣的全局變量:
int lastItemHeight = 0;
而在活動(或片段,等等),您更新OnClickListener
這個值:
edittext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// set a new Thread
listview.post(new Runnable() {
@Override
public void run() {
// get last visible position of items
int lastPosition = listview.getLastVisiblePosition() - 1;
// if the view's last child can be retrieved
if (listview.getChildAt(lastPosition) != null) {
// update the height of the last child in custom listview
listview.lastItemHeight = listview.getChildAt(lastPosition).getHeight();
}
}
});
}
});
注意: there is another possible solution但您必須在列表視圖上設置android:stackFromBottom="true"
,該列表視圖從底部堆疊其內容。相反,這裏的解決方案可以顯示特定的項目,而不會強迫內容從底部開始,並使用默認的列表視圖的行爲。
備註:(爲了以防萬一)不要忘記在清單中添加android:windowSoftInputMode="adjustResize"
。
嘗試 http://stackoverflow.com/questions/16133706/push-listview-when-keyboard-appears-without-adjustpan http://stackoverflow.com/questions/9351509/keeping-the -last-visible-item-of-listview-when-the-size-of-listview-change – MSaudi