如何在 Android 中实现文本从一个 TextView 动画过渡到另一个 TextView?
androidapps/applicationsmobile development
本示例演示如何实现文本从一个 TextView 动画过渡到另一个 TextView。
步骤 1 - 在 Android Studio 中创建一个新项目,依次点击"文件">"新建项目",并填写所有必需信息以创建一个新项目。
步骤 2 - 将以下代码添加到 res/layout/activity_main.xml 文件中。
<?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content"> <LinearLayout android:id = "@+id/parent" android:layout_width = "wrap_content" android:layout_height = "wrap_content"> <TextView android:id = "@+id/text" android:textSize = "30dp" android:textAlignment = "center" android:layout_width = "match_parent" android:textColor = "#ff4500" android:layout_height = "wrap_content" android:singleLine = "true" /> </LinearLayout> <Button android:id = "@+id/animate" android:text = "Animated button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> </RelativeLayout>
In the above code, we have taken text view and button, when user click on button, textview going to update
步骤 3 − 将以下代码添加到 src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView view = findViewById(R.id.text);
final LinearLayout parent = findViewById(R.id.parent);
view.setText("1+2");
Button animate = findViewById(R.id.animate);
animate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Animation slideUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up);
slideUp.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
view.setText("3");
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
parent.startAnimation(slideUp);
}
});
}
}
让我们尝试运行您的应用程序。我假设您已将 Android 移动设备连接到计算机。要从 Android Studio 运行应用程序,请打开项目中的一个 Activity 文件,然后单击工具栏中的"运行"图标。选择您的移动设备作为选项,然后选中您的移动设备,它将显示您的默认屏幕。 −

在上方显示的初始屏幕中,当用户点击按钮时,文本视图将更新如下图所示 -



