【问题标题】:Loading an Android app with a random background color each time每次加载具有随机背景颜色的 Android 应用程序
【发布时间】:2015-05-24 05:03:51
【问题描述】:

我正在尝试每次使用随机背景颜色启动我正在处理的应用程序。我在这里看到了一些关于此的主题,但似乎没有任何帮助。

在activity_main.xml 中它有“android:background="#F799B3",这是我希望每次生成随机颜色的部分...有什么建议吗?

非常感谢。

【问题讨论】:

标签: android random background


【解决方案1】:

在您的 MainActivity.java 中将其放入 onCreate

    Random rnd = new Random();
    int color = Color.argb(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    findViewById(android.R.id.content).setBackgroundColor(color);

如果您总是想要全色,请将 argb 的第一个参数替换为 255

【讨论】:

  • 嘿,非常感谢!!工作得很好。干杯
【解决方案2】:

好的,您可以这样做。设置布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/myLayout" >



</LinearLayout>

然后你在.java上得到一个随机数

Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();

最后在onCreate方法中添加:

View layoutView = findViewById(R.id.myLayout;
layoutView.setBackgroundColor(Color.rgb(Math.round(r), 
                                        Math.round(g), 
                                        Math.round(b) ) );

【讨论】:

    【解决方案3】:
    1. 修改你的activity main xml和所有可以设置背景颜色的xmls。

      您必须从主布局中删除“android:background="#F799B3"”行。根本不要在xml中设置背景。

    2. 然后,在您的 MainActivity.java 中尝试在您膨胀布局后设置它。就像这里显示的那样:https://stackoverflow.com/users/3767038/awk

    现在,如果你在 onCreate() 中设置它,它会在你每次打开你的主要活动时改变。如果您只想在启动时使用随机颜色背景一次,则必须在应用程序中使用 SavedInstances。

    例子:

    在你的 onCreate() 中:

     int lastUsedColor = 0 ;
     if(savedInstanceState != null){
       lastUsedColor = savedInstanceState.getInt("lastUsedColor");
       findViewById(android.R.id.content).setBackgroundColor(lastUsedColor);
     }else{
       Random rnd = new 
       int newColor = Color.argb(rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
       findViewById(android.R.id.content).setBackgroundColor(newColor);
       savedInstanceState.putInt("lastUsedColor", newColor);
       lastUsedColor = newColor;
     }
    

    在您的 onSaveInstanceState(Bundle bundle) 中

    super.onSaveInstanceState(bundle);
    bundle.putInt("lastUsedColor", lastUsedColor);
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 2012-05-19
      相关资源
      最近更新 更多