您可以使用setSelectionFromTop() 并在自定义列表视图中覆盖onSizeChanged() 来实现此目的。在您的布局中,您应该有一个 RelativeLayout 有一个父容器,并将列表视图放在编辑文本上方。
通过创建您自己的列表视图并覆盖onSizeChange(),您将能够在列表视图调整大小之前获得最后一个可见项目的位置并获得它的新高度,以便最终使用其高度的偏移。
它的工作原理:您的列表会将上一个可见项目放在其顶部,您将添加像素以在其底部滚动它,就在您的编辑文本上方。
要覆盖该方法并使用偏移量显示它,请执行以下操作:
@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 之前我没有找到如何获取最后一项的高度。然后,如果您的列表视图包含多种类型的项目(没有相同的高度),我更喜欢在事件发生时获取选定的高度,就在软键盘打开之前。
所以在自定义列表视图中,你有这个全局变量:
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"。