1

I have a app with a button and a Tool bar. I want to change the Tool bar color when button clicked. I don't want to launch any other activity, I just want when user click button the color of my Toolbar get changes.

Abdul.Moqueet
  • 902
  • 12
  • 19

2 Answers2

4

Try this

getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorAccent)));

UPDATE

To change color of status bar you should add this code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.BLUE);
}
Dushyant Suthar
  • 673
  • 2
  • 9
  • 27
0

Try This It will Work -

In XML

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorControlActivated"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/but"
    android:text="ClickME" />

In Java

public class barTool extends AppCompatActivity {
Toolbar myToolbar;
Button myButton;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.toolbar);

    myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    myButton=(Button)findViewById(R.id.but);
    setSupportActionBar(myToolbar); //Setting the Toolbar
    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myToolbar.setBackgroundColor(Color.BLACK); //Changing to Color to Black OnClick of Button
        }
    });
}}

and if error comes

This Activity already has an action bar supplied by the window decor

Remove Previous Action Bar By Setting The below code in Styles.xml

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowActionBar">false</item> <!--by setting last two the error is removed-->
<item name="windowNoTitle">true</item>

This code is taken from this link.Please See this Link Also.

Community
  • 1
  • 1
Adi
  • 903
  • 2
  • 15
  • 25