动态更改spalsh屏幕的背景颜色

时间:2018-08-23 15:52:39

标签: java android

我正在使用以下文章为我的应用创建启动画面(不对其进行任何活动):

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

工作正常。虽然,我想基于SharedPreferences值更改背景色。我知道我无法直接更改xml背景颜色值。因此,我想知道是否存在另一种设置背景颜色或将其映射为SharedPrefences值的方法。

谢谢。

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

android:theme="@style/SplashTheme"

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

setTheme(R.style.AppTheme);

1 个答案:

答案 0 :(得分:1)

共享首选项实施:

private SharedPreferences pref;

然后加载

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

现在,如果用户更改了颜色,则必须像这样保存它

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

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

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();

相关问题