Android-View-Animation 编辑框抖动shake

本文介绍如何在Android应用中实现一个简单的视图摇晃动画效果。通过自定义动画和交互逻辑,当用户点击登录按钮时,输入框将执行预设的摇晃动画。涉及的主要步骤包括创建Activity、设置布局文件及定义动画文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

截图如下:



1. Activity 很简单,如下:

package com.example.viewanimationshake;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements View.OnClickListener {
	private Button button;
	private EditText editText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		button = (Button) findViewById(R.id.login);
		editText = (EditText) findViewById(R.id.pw);
		button.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		editText.startAnimation(shake);
	}

}

2.布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    
    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"
        android:text="请输入您的密码:"
    />
    
    <EditText android:id="@+id/pw"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:singleLine="true"
        android:inputType="textPassword"
    />

    <Button android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录"
    />

</LinearLayout>

3.动画的两个文件

<?xml version="1.0" encoding="utf-8"?>
<!-- interpolator 翻译为“内插程序”,

官方文档解释:An interpolator defines the rate of change of an animation. 
This allows the basic animation effects (alpha, scale, translate, rotate) 
to be accelerated, decelerated, repeated, etc. 

通俗来讲就是android:interpolator 这个属性允许对动画做些改变,如加速,重复等。
"@anim/cycle_7" 是对自定义interpolator 的引用。-->
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fromXDelta="0"
    android:interpolator="@anim/cycle_7"
    android:toXDelta="10" />

<?xml version="1.0" encoding="utf-8"?>
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
    android:cycles="7" />

源代码在这里: 点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值