按钮-在点击时改变背景颜色

时间:2022-11-20 11:19:20

I have 8 buttons in my activity. What I am looking for is, The buttons have a default background and when a button is clicked, the background color should change to some other color. This part is pretty straight forward. But, when I click on any other button, the background color of the first button should change back to default color. I understand that this will be done using "selector states", but I am not quite sure of how to implement it. The more i read about it, the more confused I am.

我的活动中有8个按钮。我要找的是,这些按钮有一个默认的背景,当一个按钮被点击时,背景颜色应该变成其他颜色。这部分很直接。但是,当我点击任何其他的按钮时,第一个按钮的背景颜色应该更改为默认颜色。我知道这将使用“selector state”完成,但我不太确定如何实现它。我读得越多,就越糊涂。

Right now, the xml that I have is as follows: in drawable folder

现在,我拥有的xml如下所示:在drawable文件夹中

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/blue" android:state_pressed="true"/>
    <item android:drawable="@color/dark_grey" android:state_focused="true"/>  
    <item android:drawable="@drawable/image_border"/>

 </selector>

the drawable/image_border in the xml is used to define shape for the button. Below is the image_border.xml

xml中的drawable/image_border用于为按钮定义形状。下面是image_border.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="@color/dark_grey" />

    <stroke
        android:width="4dp"
        android:color="@color/light_grey" />

    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />

</shape>

Can someone help me with how to change the xml to behave the way I need it to be?

有人能帮我改变xml的行为方式吗?

[EDIT 1]

(编辑(1)

All the below answers are pointing towards similar kind of solution. Here are the changes that I did. But, still, when i press the button, it turns to the specified color but immediately turns back to the default color.

下面所有的答案都指向类似的解决方案。这是我所做的改变。但是,当我按下按钮时,它仍然会转到指定的颜色,但是会立即转回默认的颜色。

button_background_blue.xml

button_background_blue.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/image_border_blue" android:state_pressed="true"/>
    <item android:drawable="@color/dark_grey" android:state_focused="true"/>  
    <item android:drawable="@drawable/image_border"/>

 </selector>

image_border_blue.xml

image_border_blue.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="@color/blue" />

    <stroke
        android:width="4dp"
        android:color="@color/blue" />

    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />

</shape>

Any thoughts?

任何想法吗?

5 个解决方案

#1


8  

Create a shape named button_pressed.xml as follows....

创建一个名为button_pressed的形状。xml如下....

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@color/blue" />

    <stroke
        android:width="4dp"
        android:color="@color/blue" />

    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />

</shape>

Suppose, you have tow button whose ids are R.id.btn and R.id.btn1 as follows...

假设有一个id为r的tow按钮。btn R.id。btn1如下…

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:background="@drawable/button_pressed"
        android:onClick="onClick"
        android:text="Press Me 1" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:background="@drawable/button_pressed"
        android:onClick="onClick"
        android:text="Press Me 2" />

</LinearLayout>

Write onClick() method as follows...which will allow you to retain the changed color until another button pressed.

写入onClick()方法如下…这将允许您保留更改的颜色,直到另一个按钮按下。

Button button;

public void onClick(View v) {

    Drawable dr = getResources().getDrawable(R.drawable.button_pressed);
    dr.setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.SRC_ATOP);

    switch (v.getId()) {
    case R.id.btn:

        if (button == null) {
            button = (Button) findViewById(v.getId());
        } else {
            button.setBackgroundResource(R.drawable.button_pressed);
            button = (Button) findViewById(v.getId());
        }
        button.setBackgroundDrawable(dr);

        break;

    case R.id.btn2:
        if (button == null) {
            button = (Button) findViewById(v.getId());
        } else {
            button.setBackgroundResource(R.drawable.button_pressed);
            button = (Button) findViewById(v.getId());
        }
        button.setBackgroundDrawable(dr);

        break;

    default:
        break;
    }
}

I think, now you will get What you wanted to do.

我想,现在你会得到你想要的。

#2


11  

use this selector & put it in drawable folder & set button background to this selector.

使用此选择器并将其放入可绘制文件夹&设置此选择器的按钮背景。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@color/blue" android:state_pressed="true"/>
<item android:drawable="@color/AliceBlue" android:state_focused="true"/>  
<item android:drawable="@color/Azure"/>

 </selector>

OR You can use Color instead of Background. hope it helps.

或者你可以用颜色代替背景。希望它可以帮助。

#3


8  

I suggest you this selector.

我建议你使用这个选择器。

Just create a simple selector.xml file in drawable folder and then add the selector to your button as android:background="@drawable/selector" or by code like this: yourButton.setBackground(getResources().getDrawable(R.drawable.selector));

只需创建一个简单的选择器。在可绘制文件夹中的xml文件,然后将选择器添加到您的按钮中,如android:background=“@drawable/selector”或代码如下:yourButton.setBackground().getDrawable(R.drawable.selector);

selector.xml:

selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true"
        android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_enabled="true"
        android:state_focused="true" android:drawable="@android:color/holo_green_dark" />
    <item android:state_enabled="true"
        android:state_selected="true" android:drawable="@android:color/holo_purple" />
    <item
        android:drawable="@drawable/yourdrawable" />
</selector>

The first item is for pressed, the second for focused and the last is for selected state.

第一个条目用于按压,第二个条目用于聚焦,最后一个条目用于选择的状态。

#4


1  

changing background color in layout when respective color button is clicked in android

在android中单击相应的颜色按钮时,改变布局中的背景颜色

main_layout.xml

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#b056ff"
    android:id="@+id/l1">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b1"
        android:layout_gravity="center"
        android:text="RED"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b2"
        android:layout_gravity="center"
        android:text="GREEN" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b3"
        android:layout_gravity="center"
        android:text="BLUE"/>

MyActivity.java

MyActivity.java

package ram.android.com.cwp1;

import android.app.Activity;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

/**
 * Created by VENKATESH on 10-Jun-16.
 */
public class MyActivity extends Activity implements View.OnClickListener {
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    Button r, g, b;
    LinearLayout ll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        ll = (LinearLayout) findViewById(R.id.l1);
        r = (Button) findViewById(R.id.b1);
        g = (Button) findViewById(R.id.b2);
        b = (Button) findViewById(R.id.b3);
        r.setOnClickListener(this);
        g.setOnClickListener(this);
        b.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.b1:
                ll.setBackgroundColor(Color.RED);
                break;

            case R.id.b2:
                ll.setBackgroundColor(Color.GREEN);
                break;
            case R.id.b3:
                ll.setBackgroundColor(Color.BLUE);
                break;

        }

    }
}

#5


0  

I know it is very late but I hope some one would find useful. I have very simple solution, I have used in my app and works awesome.

我知道已经很晚了,但我希望有人能从中受益。我有一个非常简单的解决方案,我已经在我的应用中使用过,并且工作得非常出色。

Let me explain the logic, 1. Keep track of 2 button clicks - previous button clicked and current button clicked. I am using ArrayList 2. for every button click keep updating the previous and current button clicks value in ArrayList. 3. change the background color of previous button clicked. 4. change the background color of current button clicked.

我来解释一下逻辑,1。跟踪2个按钮点击-以前的按钮点击和当前按钮点击。我用的是ArrayList 2。对于每个按钮单击,保持更新之前和当前按钮单击ArrayList中的值。3所示。改变先前按钮点击的背景颜色。4所示。改变当前按钮点击的背景颜色。

I hope the logic is simple and straightforward.

我希望逻辑简单明了。

Here is the implementation

这是实现

xml

xml

<Button
            android:onClick="onClickRosterDay"
            android:text="Mon"
            android:textColor="@color/textColorWhite"
            android:background="@color/colorAccent"
            android:id="@+id/rosterMonday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

the OnClick method is defined for every button in XML, in the example it is onClickRosterDay

OnClick方法为XML中的每个按钮定义,在示例中是onClickRosterDay

Java

Java

 //buttons 

    Button rosterMonday;
    Button rosterTuesday;
    Button rosterWednesday;
    Button rosterThursday;
    Button rosterFriday;
    Button rosterSaturday;

    //ArrayList to track button clicks
    private ArrayList<Button> buttonClickedDay;

    in OnCreate

    buttonClickedDay = new ArrayList<>();
    // to start with these are the default clicks. 
    buttonClickedDay.add(rosterMonday ); //previous button clicked
    buttonClickedDay.add(rosterMonday ); // current button clicked



    public void onClickRosterDay(View v) {
            switch (v.getId()){
                case R.id.rosterMonday:
                    daySelected = "MONDAY";
                    // move current click button to previous button clicked position
                    buttonClickedDay.set(0, buttonClickedDay.get(1)); 
                    // update current clicked position
                    buttonClickedDay.set(1,rosterMonday);
                    break;

                case R.id.rosterTuesday:
                    daySelected = "TUESDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterTuesday);
                    break;

                case R.id.rosterWednesday:
                    daySelected = "WEDNESDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterWednesday);
                    break;

                case R.id.rosterThursday:
                    daySelected = "THURSDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterThursday);
                    break;

                case R.id.rosterFriday:
                    daySelected = "FRIDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterFriday);
                    break;

                case R.id.rosterSaturday:
                    daySelected = "SATURDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterSaturday);
                    break;
            }





        if(buttonClickedDay.get(0) != buttonClickedDay.get(1)) {
            // update background color of  previous button clicked    
buttonClickedDay.get(0).setBackgroundColor(this.getResources().getColor(R.color.colorAccent));
            // update background color of  current button clicked      
buttonClickedDay.get(1).setBackgroundColor(this.getResources().getColor(R.color.textBackgroundGreen));
        }
    }

#1


8  

Create a shape named button_pressed.xml as follows....

创建一个名为button_pressed的形状。xml如下....

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@color/blue" />

    <stroke
        android:width="4dp"
        android:color="@color/blue" />

    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />

</shape>

Suppose, you have tow button whose ids are R.id.btn and R.id.btn1 as follows...

假设有一个id为r的tow按钮。btn R.id。btn1如下…

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:background="@drawable/button_pressed"
        android:onClick="onClick"
        android:text="Press Me 1" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:background="@drawable/button_pressed"
        android:onClick="onClick"
        android:text="Press Me 2" />

</LinearLayout>

Write onClick() method as follows...which will allow you to retain the changed color until another button pressed.

写入onClick()方法如下…这将允许您保留更改的颜色,直到另一个按钮按下。

Button button;

public void onClick(View v) {

    Drawable dr = getResources().getDrawable(R.drawable.button_pressed);
    dr.setColorFilter(Color.parseColor("#FF0000"), PorterDuff.Mode.SRC_ATOP);

    switch (v.getId()) {
    case R.id.btn:

        if (button == null) {
            button = (Button) findViewById(v.getId());
        } else {
            button.setBackgroundResource(R.drawable.button_pressed);
            button = (Button) findViewById(v.getId());
        }
        button.setBackgroundDrawable(dr);

        break;

    case R.id.btn2:
        if (button == null) {
            button = (Button) findViewById(v.getId());
        } else {
            button.setBackgroundResource(R.drawable.button_pressed);
            button = (Button) findViewById(v.getId());
        }
        button.setBackgroundDrawable(dr);

        break;

    default:
        break;
    }
}

I think, now you will get What you wanted to do.

我想,现在你会得到你想要的。

#2


11  

use this selector & put it in drawable folder & set button background to this selector.

使用此选择器并将其放入可绘制文件夹&设置此选择器的按钮背景。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@color/blue" android:state_pressed="true"/>
<item android:drawable="@color/AliceBlue" android:state_focused="true"/>  
<item android:drawable="@color/Azure"/>

 </selector>

OR You can use Color instead of Background. hope it helps.

或者你可以用颜色代替背景。希望它可以帮助。

#3


8  

I suggest you this selector.

我建议你使用这个选择器。

Just create a simple selector.xml file in drawable folder and then add the selector to your button as android:background="@drawable/selector" or by code like this: yourButton.setBackground(getResources().getDrawable(R.drawable.selector));

只需创建一个简单的选择器。在可绘制文件夹中的xml文件,然后将选择器添加到您的按钮中,如android:background=“@drawable/selector”或代码如下:yourButton.setBackground().getDrawable(R.drawable.selector);

selector.xml:

selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true"
        android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_enabled="true"
        android:state_focused="true" android:drawable="@android:color/holo_green_dark" />
    <item android:state_enabled="true"
        android:state_selected="true" android:drawable="@android:color/holo_purple" />
    <item
        android:drawable="@drawable/yourdrawable" />
</selector>

The first item is for pressed, the second for focused and the last is for selected state.

第一个条目用于按压,第二个条目用于聚焦,最后一个条目用于选择的状态。

#4


1  

changing background color in layout when respective color button is clicked in android

在android中单击相应的颜色按钮时,改变布局中的背景颜色

main_layout.xml

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#b056ff"
    android:id="@+id/l1">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b1"
        android:layout_gravity="center"
        android:text="RED"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b2"
        android:layout_gravity="center"
        android:text="GREEN" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b3"
        android:layout_gravity="center"
        android:text="BLUE"/>

MyActivity.java

MyActivity.java

package ram.android.com.cwp1;

import android.app.Activity;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

/**
 * Created by VENKATESH on 10-Jun-16.
 */
public class MyActivity extends Activity implements View.OnClickListener {
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    Button r, g, b;
    LinearLayout ll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        ll = (LinearLayout) findViewById(R.id.l1);
        r = (Button) findViewById(R.id.b1);
        g = (Button) findViewById(R.id.b2);
        b = (Button) findViewById(R.id.b3);
        r.setOnClickListener(this);
        g.setOnClickListener(this);
        b.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.b1:
                ll.setBackgroundColor(Color.RED);
                break;

            case R.id.b2:
                ll.setBackgroundColor(Color.GREEN);
                break;
            case R.id.b3:
                ll.setBackgroundColor(Color.BLUE);
                break;

        }

    }
}

#5


0  

I know it is very late but I hope some one would find useful. I have very simple solution, I have used in my app and works awesome.

我知道已经很晚了,但我希望有人能从中受益。我有一个非常简单的解决方案,我已经在我的应用中使用过,并且工作得非常出色。

Let me explain the logic, 1. Keep track of 2 button clicks - previous button clicked and current button clicked. I am using ArrayList 2. for every button click keep updating the previous and current button clicks value in ArrayList. 3. change the background color of previous button clicked. 4. change the background color of current button clicked.

我来解释一下逻辑,1。跟踪2个按钮点击-以前的按钮点击和当前按钮点击。我用的是ArrayList 2。对于每个按钮单击,保持更新之前和当前按钮单击ArrayList中的值。3所示。改变先前按钮点击的背景颜色。4所示。改变当前按钮点击的背景颜色。

I hope the logic is simple and straightforward.

我希望逻辑简单明了。

Here is the implementation

这是实现

xml

xml

<Button
            android:onClick="onClickRosterDay"
            android:text="Mon"
            android:textColor="@color/textColorWhite"
            android:background="@color/colorAccent"
            android:id="@+id/rosterMonday"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

the OnClick method is defined for every button in XML, in the example it is onClickRosterDay

OnClick方法为XML中的每个按钮定义,在示例中是onClickRosterDay

Java

Java

 //buttons 

    Button rosterMonday;
    Button rosterTuesday;
    Button rosterWednesday;
    Button rosterThursday;
    Button rosterFriday;
    Button rosterSaturday;

    //ArrayList to track button clicks
    private ArrayList<Button> buttonClickedDay;

    in OnCreate

    buttonClickedDay = new ArrayList<>();
    // to start with these are the default clicks. 
    buttonClickedDay.add(rosterMonday ); //previous button clicked
    buttonClickedDay.add(rosterMonday ); // current button clicked



    public void onClickRosterDay(View v) {
            switch (v.getId()){
                case R.id.rosterMonday:
                    daySelected = "MONDAY";
                    // move current click button to previous button clicked position
                    buttonClickedDay.set(0, buttonClickedDay.get(1)); 
                    // update current clicked position
                    buttonClickedDay.set(1,rosterMonday);
                    break;

                case R.id.rosterTuesday:
                    daySelected = "TUESDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterTuesday);
                    break;

                case R.id.rosterWednesday:
                    daySelected = "WEDNESDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterWednesday);
                    break;

                case R.id.rosterThursday:
                    daySelected = "THURSDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterThursday);
                    break;

                case R.id.rosterFriday:
                    daySelected = "FRIDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterFriday);
                    break;

                case R.id.rosterSaturday:
                    daySelected = "SATURDAY";
                    buttonClickedDay.set(0, buttonClickedDay.get(1));
                    buttonClickedDay.set(1,rosterSaturday);
                    break;
            }





        if(buttonClickedDay.get(0) != buttonClickedDay.get(1)) {
            // update background color of  previous button clicked    
buttonClickedDay.get(0).setBackgroundColor(this.getResources().getColor(R.color.colorAccent));
            // update background color of  current button clicked      
buttonClickedDay.get(1).setBackgroundColor(this.getResources().getColor(R.color.textBackgroundGreen));
        }
    }