listview 设置某行位置位于键盘顶部

最近需要做个功能,就像微信朋友圈那样点击某个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;
                                    }
                                }
                            } 
                        }
                    }
                });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值