这是一个可以在横屏模式下显示当前时间并实时更新,文字变化带有动画效果的 Android 完整示例。
首先,在 MainActivity.java 文件中创建一个名为 MainActivity 的 Activity,并设置布局和逻辑。
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private TextView timeTextView;
private Handler handler = new Handler();
private Animation textAnimation;
private Runnable updateTimeRunnable = new Runnable() {
@Override
public void run() {
updateTime();
timeTextView.startAnimation(textAnimation);
handler.postDelayed(this, 1000); // 每秒钟更新一次时间
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
timeTextView = findViewById(R.id.timeTextView);
textAnimation = AnimationUtils.loadAnimation(this, R.anim.text_animation);
updateTime();
startUpdateTime();
}
@Override
protected void onDestroy() {
super.onDestroy();
stopUpdateTime();
}
private void startUpdateTime() {
handler.postDelayed(updateTimeRunnable, 1000);
}
private void stopUpdateTime() {
handler.removeCallbacks(updateTimeRunnable);
}
private void updateTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
String currentTime = sdf.format(new Date());
timeTextView.setText(currentTime);
}
}
接下来,在 res 目录下创建 anim 文件夹,并在 anim 文件夹中创建名为 text_animation.xml 的 XML 文件。
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="500" />
<scale
android:fromXScale="2.0"
android:fromYScale="2.0"
android:toXScale="1.0"
android:toYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="500" />
</set>
在上述代码中,我们使用 AlphaAnimation 实现了透明度的变化动画效果,从 0 到 1,持续 500 毫秒;使用 ScaleAnimation 实现了缩放的动画效果,从 2 倍大小到正常大小,持续 500 毫秒。然后我们将这两个动画效果合并在一个 <set> 标签中。
最后,在 activity_main.xml 文件中定义布局。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<TextView
android:id="@+id/timeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="72sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true" />
</RelativeLayout>
在上述代码中,我们创建了一个 Activity MainActivity,并在 onCreate 方法中设置布局和横屏模式。我们使用一个 TextView 来显示时间,并使用 Handler 和 Runnable 实现时间的实时更新。
在 updateTime 方法中,我们使用 SimpleDateFormat 将当前时间格式化为 "HH:mm:ss" 的字符串,并将其设置到 timeTextView 中。
我们还定义了一个 textAnimation 对象,它从 R.anim.text_animation 文件中加载了动画效果,其中定义了透明度和缩放的变化。
最后,在 onDestroy 方法中停止更新时间的任务,以避免在 Activity 销毁后继续更新时间。