Android 开发收集的一些东西

优雅的设计启动页

2020-02-07  本文已影响0人  A_si

设计一个启动页的两种方式

app 越来越复杂,主页启动越来越耗时,并且往往需要预加载数据,这时候先展示一个启动页就显得十分有必要了。流行的 app 一般都采用这种做法。

我们知道,如果第一屏启动的慢,那么会默认展示一个黑屏的缺省页,这个黑色是默认的 windowBackground 的颜色,许多启动优化的操作里,会修改 windowBackground 默认展示一张启动图片。

更改启动背景

为了不和默认主题混淆,首先需要声明一个启动主题,只设置给启动页:

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <!--    启动页主题-->
    <style name="AppTheme.Splash" parent="AppTheme">
        <item name="android:windowBackground">@drawable/splash_drawable</item>
    </style>

启动页一般是显示一个 logo ,下面使用 layer-list 描绘出启动页布局 splash_drawable :

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorWhite" />
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/ic_zhanweifu"></bitmap>
    </item>
</layer-list>

然后设置给主页:

        <activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme.Splash">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
Screenshot_1578046119.png Screenshot_1578046086.png

启动应用,会看到先看到 splash_drawable 而不是原来默认的黑屏 ,但是 MainActivity 的 背景也和 splash_drawable 一样了。 因为窗口背景被设置成 splash_drawable ,通过 setContentView() 设置的布局都会在 这个背景上绘制,所以我们需要在 setContentView() 把主题设置为默认的:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTheme(R.style.AppTheme)
        setContentView(R.layout.activity_splash)
    }
}
Screenshot_1578046141.png

设置启动页

上面的方法适合简单的静态的启动页,但是也有许多 app 会加上倒计时或者广告,那么只改启动背景就不能实现了。这是个需要一个单独的 activity 来实现:

class SplashActivity : AppCompatActivity() {

    /**
     * CountDownTimer 实现倒计时
     */
    private val countDownTimer = object : CountDownTimer(3000, 1000) {
        override fun onFinish() {
            Intent(this@SplashActivity, MainActivity::class.java).also {
                startActivity(it)
            }
        }

        override fun onTick(millisUntilFinished: Long) {
            (millisUntilFinished / 1000).toString().let {
                tvCountDown.text = it
            }
        }
    };


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTheme(R.style.AppTheme)
        setContentView(R.layout.activity_splash)
        countDownTimer.start()
    }
}

这是一个3秒倒计时的启动页,3秒后跳转主页。当然别忘记在页面 destroy 的时候取消倒计时防止内存泄漏。

上一篇 下一篇

猜你喜欢

热点阅读