简体   繁体   English

如何更改按钮单击时的工具栏颜色?

[英]How to change toolbar color on button click?

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. 我不想启动任何其他活动,我只想在用户点击按钮时我的工具栏的颜色得到改变。

Try this 尝试这个

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

UPDATE 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);
}

Try This It will Work - 试试这个会工作 -

In XML 在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 在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 通过在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. 此代码取自此链接 。请参阅此链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM