Android,点击EdiText后,控件慢慢变长

当看见这个需求时,觉得很简单,一个动画: 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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值