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

How to get the height of each line in edit text

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

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();
        }
    }

但是,正如您在动画中看到的那样,我添加了一个随机值,例如 60。但是,这对所有设备来说都不可靠。

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

提前致谢

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);

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

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 
};