java - 动态更改初始屏幕的背景颜色
问题描述
我正在使用以下文章为我的应用程序制作启动画面(不为它做任何活动):
https://www.bignerdranch.com/blog/splash-screens-the-right-way/
它工作正常。不过,我想根据一个SharedPreferences
值更改背景颜色。我知道我不能直接更改 xml 背景颜色值。所以,我想知道是否有另一种方法来设置背景颜色或将其映射到一个SharedPrefences
值。
谢谢你。
编辑:我想避免为启动屏幕创建新活动。澄清我目前正在使用的内容。我有:
android:theme="@style/SplashTheme"
在清单上设置应用程序主题。然后,在 MainActivity 我使用:
setTheme(R.style.AppTheme);
解决方案
共享首选项实现:
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();
推荐阅读
- firebase - 通过 REST API 从 Firebase 实时数据库中删除最后一个节点
- wordpress - 阻止来自服务器名称的访问
- sql - SQL:如何提高视图的 SQL 查询性能?
- java - AbstractProcessor 可以检测带注释的方法是否存在编译错误?
- c - 在 C 中计算大小写字母的问题
- spring-boot - 使用 Spring Boot 和 Heroku 时,H2 数据库在哪里?
- python - Pandas:如何查找范围之间的值的索引
- angular - 带一个输入的切换器的角形
- airflow - Apache Airflow - 在接下来的步骤中使用 python 结果
- java - 在 Android 中的绘制/布局操作错误期间避免对象分配