1. Tạo Drawable: splash_background.xml
- Tạo file: /app/res/drawable/splash_background.xml
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/colorPrimary"/> <item android:drawable="@mipmap/ic_launcher" android:gravity="center"/> </layer-list> |
2. Thêm SplashTheme trong Styles
- Sửa file: /app/res/values/styles.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="SplashTheme" parent="Theme.AppCompat.DayNight.NoActionBar"> <item name="android:windowBackground">@drawable/splash_background</item> </style> </resources> |
3. Tạo Activity: SplashScreenActivity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.example.musicplayer; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; public class SplashScreenActivity extends AppCompatActivity { private int splash_time_out = 500; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(SplashScreenActivity.this,MainActivity.class); startActivity(intent); finish(); } },splash_time_out); } } |
4. Dùng SplashScreenActivity làm Activity khởi chạy app
- Sửa file: app/manifests/AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.musicplayer"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:theme="@style/SplashTheme" android:name=".SplashScreenActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".PlayingActivity" /> <activity android:name=".MainActivity"> </activity> </application> </manifest> |
5. Vấn đề khác
- SplashScreen sẽ mượt mà nhất khi chỉ set Theme cho Activity thôi.
- Nếu muốn SplashScreen có thêm tiến tình như ProgessBar, ... thì tại SplashScreenActivity phải setContentView như bình thường