-1

Я хочу создать случайно Actionbar и Status bar в onCreate, с заданным цветом (оранжевый, зеленый и розовый). Я нашел полезный код ниже:Как создать случайную панель действий и строку состояния Oncreate mode

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

вы хотите изменить цвет каждый раз, когда активность получить открытой или что? –

+0

@SwapnilMeshram да, точно –

ответ

1

Вы можете просто создать массив цвета в color.xml и выбрать случайный цвет от него, чтобы установить цвет ActionBar, а также в строке состояния цвета.

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> 

В вашей деятельности

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]; 
} 
1

Это работает для меня, вы также можете увидеть, как какой-то экспериментальный код прокомментирован. Я использую AppCompatActivity.

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.mylayout); 
    setupActionBar(); 
} 

    private void setToolbarColor() { 
     final int toolbarColor = getResources().getColor(R.id.color_orange); 

     // create our manager instance after the content view is set 
     final SystemBarTintManager tintManager = new SystemBarTintManager(this); 
     // enable status bar tint 
     tintManager.setStatusBarTintEnabled(true); 
     // enable navigation bar tint 
     tintManager.setNavigationBarTintEnabled(true); 

     // set a custom tint color for all system bars 
     tintManager.setTintColor(toolbarColor); 

//  // set a custom navigation bar resource 
//  tintManager.setNavigationBarTintResource(R.drawable.my_tint); 
//  // set a custom status bar drawable 
//  tintManager.setStatusBarTintDrawable(MyDrawable); 

     final ActionBar actionBar = getSupportActionBar(); 
     if (null != actionBar) { 
//  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
//   Window.setStatusBarColor(); 
//   getWindow().setStatusBarColor(Color.BLUE); 
//  } 
      actionBar.setBackgroundDrawable(new ColorDrawable(toolbarColor)); 
     } 
    }