Search code examples
javaandroidandroid-studioandroid-actionbarandroid-statusbar

How to create random Actionbar and status bar Oncreate mode


I want to create random Actionbar and Status bar in onCreate, With specified color (orange, green and pink). I found some useful code below:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ActionBar actionBar; 
    actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#879f38")));

Solution

  • You can simply create array of color in color.xml and pick a random color from it to set the actionbar color as well as status bar color.

    color.xml
    
     <array name="actionbar_color">
        <item>@color/bright_pink</item>
        <item>@color/red</item>
        <item>@color/orange</item>
        <item>@color/yellow</item>
        <item>@color/chartreuse</item>
        <item>@color/green</item>
        <item>@color/spring_green</item>
        <item>@color/cyan</item>
        <item>@color/azure</item>
        <item>@color/blue</item>
        <item>@color/violet</item>
        <item>@color/magenta</item>
    </array>
    

    In your activity

     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);     
    
    // further code
    
    int[] actionbarColor = context.getResources().getIntArray(R.array.actionbar_color);
    actionBar.setBackgroundDrawable(new ColorDrawable(getRandom(actionbarColor)));
    }
    
    public int getRandom(int[] array) {
    int rnd = new Random().nextInt(array.length);
    return array[rnd];
    }