繁体   English   中英

如何在编辑文本中获取每行的高度

[英]How to get the height of each line in edit text

我想在添加或删除新行时为键盘设置动画,就像电报一样。 我可以这样添加 animation:

private void doAnimation(int linesCount, String s){
        Toast.makeText(this, "" + linesCount, Toast.LENGTH_SHORT).show();
        if (linesCount == 1){
            binding.message.getLayoutParams().height = defEditTextHeight;
            return;
        }
        if (linesCount < binding.message.getLineCount()) {
            ValueAnimator anim = ValueAnimator.ofInt(binding.message.getHeight(), binding.message.getHeight() + 60)
                    .setDuration(250);
            anim.addUpdateListener(animation -> {
                binding.message.getLayoutParams().height = (int) animation.getAnimatedValue();
                binding.message.requestLayout();
            });
            anim.start();
        }else if( linesCount > binding.message.getLineCount()){
            ValueAnimator anim = ValueAnimator.ofInt(binding.message.getHeight(), binding.message.getHeight() - 60)
                    .setDuration(250);
            anim.addUpdateListener(animation -> {
                binding.message.getLayoutParams().height = (int) animation.getAnimatedValue();
                binding.message.requestLayout();
            });
            anim.start();
        }
    }

但是,如您所见,对于 animation,我添加了一个随机值,如 60。但是,这对所有设备来说都不可靠。

那么,我怎样才能得到每一行的高度,以便我可以添加它并得到一个好的 animation?

提前致谢

EditText 每行的高度由 EditText创建StaticLayout指定。

// Get vertical padding of the EditText
int padding = binding.message.getPaddingTop() + binding.message.getPaddingBottom();

// Get the total height of the EditText
int totalHeight = binding.message.getLayout().getHeight() + padding;
// or
int totalHeight = binding.message.getHeight();

// Get the height that line i contributes to the EditText. 
int height = binding.message.getLayout().getLineBottom(i) - binding.message.getLayout().getLineTop(i);

因此,您的 animation 定义将如下所示:

int i = linesCount - 1;
int height = binding.message.getLayout().getLineBottom(i) - binding.message.getLayout().getLineTop(i);
ValueAnimator anim = ValueAnimator.ofInt(binding.message.getHeight(), binding.message.getHeight() + height)
                .setDuration(250);

如果需要等待布局,可以使用如下:

binding.message.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
    // code here 
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM