最近需要做个功能,就像微信朋友圈那样点击某个item时,会调整item的位置在输入框上面。在网上找了些资料完成了这个功能,记录一下
Window mRootWindow = getWindow();
View mRootView = mRootWindow.getDecorView().findViewById(
android.R.id.content);
mRootView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
Rect r = new Rect();
View view = mRootWindow.getDecorView();
view.getWindowVisibleDisplayFrame(r);
//进入应用后会首先调一次这个方法,contentHeight为去掉状态栏屏幕的高度
if (isFirst) {
contentHeight = r.bottom - r.top;
isFirst = false;
}
// 当输入法弹起时r.bottom-r.top为输入法顶部到状态栏底部的高度
if (r.bottom - r.top != contentHeight) {
int lastHeight = 0;
if (!isKeyboard) {//输入法弹起的一个flag,此处设置主要是因为下面调整listview时onGlobalLayout()方法会循环调用,设置后避免它循环进入方法
height = 0;
//curPosition为当前点击的行position
for (int i = curPosition; i >= 0; i--) {
View item = adapter.getView(i, null,
listview);
item.measure(0, 0);//此处item(item可能为header)的根布局为LinearLayout,否则会报空指针异常
if(i==curPosition){
//currentHeight 为当前行的高度
currentHeight = item.getMeasuredHeight();
}
//height为计算当前行底部到listview控件顶部,此处listview之上没有其他视图了
height += item.getMeasuredHeight();
if (height > r.bottom - r.top) {
listview.setSelectionFromTop(
curPosition,
r.bottom- r.top- currentHeight);//当前行到顶部的偏移量
isKeyboard = true;
break;
}
}
}
}
}
});