当看见这个需求时,觉得很简单,一个动画: ObjectAnimator.ofFloat(editText, “scaleX”, 1f,2f).setDuration(1000).start()就可以解决或者ScaleAnimation类就可以解决。但是发现,输入时EditText中的字体被拉伸。然后试着设置editText.setTextScaleX来解决字体被拉伸的问题,可输入字符太多还是有问题,蛋疼呀。于是想着,要不来个组合动画AnimatSet,设置两个EditText,这里就叫做EditTextA,EditTextB(为EditTextA的动画后的最终形态)。先对EdiTextA进行变换:透明度1f到0f和宽度慢慢变长。当动画结束后,EditTextA隐藏,EditTextB显示出来。可是,发现效果还是不理想,结果就到其他开源项目看源码,发现了如下方式,代码很简单:
一.布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
tools:context=".MainActivity">
<EditText
android:id="@+id/et"
android:gravity="center"
android:hint="输入密码"
android:layout_alignParentRight="true"
android:singleLine="true"
android:textSize="14sp"
android:background="@drawable/edit_shape"
android:layout_width="150dp"
android:layout_height="40dp" />
</RelativeLayout>
二.代码:
package com.sxit.animationtest;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().getDecorView().setBackgroundResource(R.mipmap.background);
setContentView(R.layout.activity_main);
editText=findViewById(R.id.et);
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
ViewWrapper viewWrapper = new ViewWrapper(editText);
ObjectAnimator.ofInt(viewWrapper, "trueWidth", 800).setDuration(700).start();
}
});
}
private class ViewWrapper {
private View mTarget;
public ViewWrapper(View view) {
mTarget = view;
}
public void setTrueWidth(int width) {
mTarget.getLayoutParams().width = width;
mTarget.requestLayout();//必须调用,否则宽度改变但UI没有刷新
}
public int getTrueWidth() {
return mTarget.getLayoutParams().width;
}
}
}
Demo 链接如下:
https://download.csdn.net/download/jimtrency/11862930