Android Studio修改app名称、图标和启动页面

18 阅读2分钟

版权属于:胡东东博客 - hudd.cn

原文链接:blog.hudd.cn/1430.html

作为安卓开发上线最后的配置,修改app名称和图标必不可少。

APP名称

App的名字和图标读取的app/src/main/AndroidManifest.xml文件中配置,其中 标签的 android:label="@string/app_name"就是app名字,而这个@string/app_name读取的是res/values/strings.xml文件的app_name名称。

所以修改res/values/strings.xml文件,修改app_name的值即可

<resources>
    <string name="app_name">Damon胡东东</string> 
</resources>

APP图标

使用Android Studio自带的Image Asset工具生成,这样会自动在res/mipmap下生成一堆 ic_launcher 和 ic_launcher_round 图片,并自动在AndroidManifest.xml里的android:icon中引用它们。

在项目目录的 res 文件夹上右键 -> New -> Image Asset。

Icon Type 选择 Launcher Icons (Adaptive and Legacy)(自适应图标,完美适配各种圆形、方形的手机系统)。

Foreground Layer(前景层):Asset Type 选择 Image,然后在 Path 里选中你的 Logo 图片。在下面的 Resize 滑块里调整图片大小,确保它在那个圈圈安全线内。

Background Layer(背景层):可以选择一种纯色(Color)作为背景,或者另一张纯背景图。,避免空白

点击完成 Next -> Finish。每次重新生成都会覆盖更新。

APP启动图

修改完app图标之后,启动图会自动更新成中间显示app图标的形式。如果需要修改可以使用官方的androidx.core:core-splashscreen的库,不过启动图打开就秒没,并且很多会加启动的广告。所以这个需求可能不大,如果需要可以引入该库

1. 引入依赖

在app/build.gradle.kts 中添加库:

dependencies {
    implementation("androidx.core:core-splashscreen:1.0.1")
}

2. 在 themes.xml 中配置启动图样式

打开res/values/themes.xml(如果没有就创建一个),定义一个继承自Theme.SplashScreen的专门主题:

<resources>
    <style name="Theme.App.Starting" parent="Theme.SplashScreen">
        <item name="windowSplashScreenBackground">#FFFFFF</item>     
        <item name="windowSplashScreenAnimatedIcon">@mipmap/ic_launcher_foreground</item>
        <item name="windowSplashScreenAnimationDuration">0</item>
        <item name="postSplashScreenTheme">@style/Theme.YourAppTheme</item>
    </style>
</resources>

3. 在 AndroidManifest.xml 中挂载主题

把MainActivity 的主题暂时换成刚才创建的启动图主题:

<application ...>
    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:theme="@style/Theme.App.Starting"> <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

4. 挂载MainActivity

最后一步,在MainActivity的onCreate里,在setContent渲染Compose UI之前,调用一行 installSplashScreen():

import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // 必须写在 super.onCreate 之前!负责承接系统启动图,在Compose第一帧优雅地淡出
        val splashScreen = installSplashScreen()
        super.onCreate(savedInstanceState)
        
        setContent {
            YourAppTheme {
                // Your Compose UI...
                CustomUI()
            }
        }
    }
}

进阶:如果需要启动图多停留一会

如果你的页面一进来需要一些操作,想让启动图一直顶着、不让用户看到空页面,可以调用setKeepOnScreenCondition,例如

val viewModel: SearchViewModel by viewModels()

// 只要 ViewModel 里的数据还没加载完,启动图就死死卡在屏幕上不消失
splashScreen.setKeepOnScreenCondition {
    viewModel.isLoading.value
}