我们可以使用动画和布局参数来实现EditText的平滑扩展和收缩。我们需要设置EditText的maxLines为Integer.MAX_VALUE以允许多行输入。然后,我们可以使用TextChangedListener来检测当用户输入时EditText的高度是否需要扩展或收缩,并使用动画逐步更改高度值。以下是一个代码示例:
private int maxEditTextHeight;
private ObjectAnimator growAnimator, shrinkAnimator;
//在OnCreate()方法中初始化EditText的布局参数和动画
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.edit_text);
maxEditTextHeight = editText.getLayoutParams().height;
editText.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) {
Layout layout = editText.getLayout();
int height = editText.getHeight();
int newHeight = height;
if (layout != null){
int newLine = editText.getLineCount();
if (newLine > 1 && newHeight <= maxEditTextHeight) {
newHeight = layout.getHeight() + editText.getPaddingTop() + editText.getPaddingBottom();
growAnimator = ObjectAnimator.ofInt(editText.getParent(), "height", editText.getParent().getHeight(), newHeight);
growAnimator.setDuration(200).setInterpolator(new AccelerateDecelerateInterpolator());
growAnimator.start();
} else if (newLine == 1 && newHeight > maxEditTextHeight) {
newHeight = maxEditTextHeight;
shrinkAnimator = ObjectAnimator.ofInt(editText.getParent(), "height", editText.getParent().getHeight(), newHeight);
shrinkAnimator.setDuration(200).setInterpolator(new AccelerateDecelerateInterpolator());
shrinkAnimator.start();
}
}
}
});
}
在上面的代码中,“maxEditTextHeight”是初始EditText高度,我们使用TextChangedListener来检