很多软件启动时都有个闪屏,这个是怎么实现的呢?
无非就是2个Activity,第一个Activity显示几秒钟时间后关闭,再显示第二个Activity。
代码如下:
1、新建一个空的SplashDemo工程(不包含activity)
2、如果提示AppTheme没有找到可以自己添加一个themes.xml文件
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="AppTheme" parent="android:Theme.Light"> <item name="android:windowNoTitle">true</item> <item name="android:windowFullscreen">true</item> <item name="android:windowContentOverlay">@android:color/transparent</item> </style> </resources>
3、分别添加SplashActivity和MainActivity(empty activity)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.splashdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="21" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > </activity> <activity android:name=".SplashActivity" android:label="@string/title_activity_splash" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
4、给Splash添加ImageView并绑定图片
5、打开SplashActivity,添加/修改以下代码
public class SplashActivity extends Activity { private static final int MSG_LOADING_TIMEOUT = 0x00; private static final int LOADING_DELAYED = 2000; private Handler mHandler = new Handler() { /** * (non-Javadoc) * @see android.os.Handler#handleMessage(android.os.Message) */ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case MSG_LOADING_TIMEOUT: Intent intent = new Intent(SplashActivity.this, MainActivity.class); SplashActivity.this.startActivity(intent); SplashActivity.this.finish(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); this.mHandler.sendEmptyMessageDelayed(MSG_LOADING_TIMEOUT, LOADING_DELAYED); } }
6、以上基本可以实现切换,但是界面这样切换感觉比较唐突,加一个画面切换过度是不是好一些呢?
1)添加一个splash_timeout.xml文件
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:zAdjustment="top" > <translate android:duration="500" android:fromXDelta="0%" android:toXDelta="-100%" /> </set>
2)修改handleMessage
public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case MSG_LOADING_TIMEOUT: Intent intent = new Intent(SplashActivity.this, MainActivity.class); SplashActivity.this.startActivity(intent); SplashActivity.this.overridePendingTransition(0, R.anim.splash_timeout); SplashActivity.this.finish(); break; } }
这样就有了一个从右到左的切换动画。
代码下载:百度网盘