Android闪屏页、启动页的实现

实现步骤:

  1. 创建倒计时布局文件
  2. 使用 CountDownTimer实现倒计时
  3. 如何将程序第一个页面设置为启动页或欢迎页

  • 创建倒计时布局文件
<?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:background="@mipmap/img_welcome"
    tools:context=".WelcomeActivity">


    <androidx.cardview.widget.CardView
        android:layout_width="80dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_margin="20dp"
        android:backgroundTint="#20000000"
        android:elevation="0dp"
        app:cardCornerRadius="25dp">

        <TextView
            android:id="@+id/tv_countdown"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="3 s"
            android:textSize="16sp"
            android:textStyle="bold" />
    </androidx.cardview.widget.CardView>

</RelativeLayout>
  • 在WelcomeActivity中实现
public class WelcomeActivity extends AppCompatActivity {
    
    

    private TextView tvCountdown;
    private CountDownTimer countDownTimer;
    private long timeLeftInMillis = 3000; // 设置倒计时时长,单位为毫秒

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        //初始化控件
        tvCountdown = findViewById(R.id.tv_countdown);
        // 启动倒计时
        startCountdown();
    }

    private void startCountdown() {
    
    
        countDownTimer =new CountDownTimer(timeLeftInMillis,1000) {
    
    
            @Override
            public void onTick(long millisUntilFinished) {
    
    
                timeLeftInMillis = millisUntilFinished;
                int secondsRemaining = (int) (millisUntilFinished / 1000);
                tvCountdown.setText(secondsRemaining +" s");
            }

            @Override
            public void onFinish() {
    
    
                // 倒计时结束后的操作,例如跳转到主页面
                finish();
                //然后跳转到登录页面(看自己逻辑想跳转哪个页面)
                startActivity(new Intent(WelcomeActivity.this, ProductActivity.class));

            }
        }.start();

    }

    @Override
    protected void onDestroy() {
    
    
        super.onDestroy();
        if (countDownTimer != null) {
    
    
            countDownTimer.cancel();
        }
    }
}
  • 效果图

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/jky_yihuangxing/article/details/133862422