首页 > 解决方案 > 动态更改初始屏幕的背景颜色

问题描述

我正在使用以下文章为我的应用程序制作启动画面(不为它做任何活动):

https://www.bignerdranch.com/blog/splash-screens-the-right-way/

它工作正常。不过,我想根据一个SharedPreferences值更改背景颜色。我知道我不能直接更改 xml 背景颜色值。所以,我想知道是否有另一种方法来设置背景颜色或将其映射到一个SharedPrefences值。

谢谢你。

编辑:我想避免为启动屏幕创建新活动。澄清我目前正在使用的内容。我有:

android:theme="@style/SplashTheme"

在清单上设置应用程序主题。然后,在 MainActivity 我使用:

setTheme(R.style.AppTheme);

标签: javaandroid

解决方案


共享首选项实现:

private SharedPreferences pref;

然后加载它

pref = this.getSharedPreferences("myAppPref",MODE_PRIVATE);

现在如果用户改变颜色,你必须像这样保存它

pref.edit().putString("splashColor","the new color hex here ex: #FFFFFF").commit();

当用户现在重新打开(或第一次打开)时,您必须从首选项加载它并显示它:

String color= pref.getString("splashColor","your default color here ex : #000000");

在可变颜色中会有你的颜色十六进制代码

现在在splash_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    android:id="@+id/root"
    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"
    >

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        app:srcCompat="@mipmap/ic_launcher" />
</RelativeLayout>

现在在SplashActivity.java中创建:

setContentView(R.layout.splash_activity.xml);
    mRelativeLayout = findViewById(R.id.root);
    pref = this.getSharedPreferences("myAppPref",MODE_PRIVATE);
    String color = pref.getString("splashColor","your default color here ex : #000000");
    mRelativeLayout.setBackgroundColor(Color.parseColor(color));

    Handler handler = new Handler();
    int Delay = 3000; // choose ur own delay

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    },Delay);

注意:当您想要保存或更改颜色时使用它: pref.edit().putString("splashColor","the new color hex here ex: #FFFFFF").commit();


推荐阅读