android 开发 textview 自动滚动到最后

textview添加内容后,自动滚动到最后,附关键代码:

        text_log.setMovementMethod(ScrollingMovementMethod.getInstance());

        // ping 日志显示维护
        // 新增内容后自动翻到最后
        text_log.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                scrollToLastLine(text_log);
            }
            private void scrollToLastLine(TextView tv){
                int scrollY = 0;
                if(!TextUtils.isEmpty(tv.getText())){
                    final  int linesCount = tv.getLineCount();
                    if(linesCount > 0){
                        scrollY = Math.max(0,(tv.getLayout().getLineTop(linesCount)-tv.getHeight()));
                    }
                }
                tv.scrollTo(0,scrollY);
            }
        });
        ```

你可能感兴趣的:(android,java,开发语言)