简体   繁体   English

单击时如何更改 Android 中按钮的颜色?

[英]How to Change color of Button in Android when Clicked?

I am working on Android Application.我正在研究 Android 应用程序。 I want to have 4 buttons to be placed horizontally at the bottom of the screen.我想在屏幕底部水平放置 4 个按钮。 In these 4 buttons 2 buttons are having images on them.在这 4 个按钮中,有 2 个按钮上有图像。 The border of the buttons should be black color and the border should be as thin as possible.按钮的边框应为黑色,边框应尽可能细。 When I click the button, I want the background of the button should be changed to blue color without the color of border to be changed and should be remained in that color for some time.当我单击按钮时,我希望按钮的背景应更改为蓝色而不更改边框颜色,并且应保持该颜色一段时间。 How can I achieve this scenario in Android?如何在 Android 中实现此场景?

One approach is to create an XML file like this in drawable , called whatever.xml:一种方法是在drawable创建一个这样的 XML 文件,称为whatever.xml:

<?xml version="1.0" encoding="utf-8"?> 
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/bgalt" />

    <item
        android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/bgalt" />

    <item android:drawable="@drawable/bgnorm" />
</selector>

bgalt and bgnorm are PNG images in drawable. bgaltbgnorm是 drawable 中的 PNG 图像。

If you create the buttons programatically in your activity, you can set the background with:如果您在活动中以编程方式创建按钮,则可以使用以下方法设置背景:

final Button b = new Button (MyClass.this);
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.whatever));

If you set your buttons' style with an XML, you would do something like:如果您使用 XML 设置按钮的样式,您将执行以下操作:

<Button
  android:id="@+id/mybutton"
  android:background="@drawable/watever" />

And finally a link to a tutorial .最后是教程链接 Hope this helps.希望这会有所帮助。

Save this code in drawable folder with "bg_button.xml" and call "@drawable/bg_button" as background of button in your xml:将此代码保存在带有“bg_button.xml”的drawable文件夹中,并在xml中调用“@drawable/bg_button”作为按钮的背景:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#004F81" />
            <stroke
                android:width="1dp"
                android:color="#222222" />
            <corners
                android:radius="7dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#89cbee"
                android:endColor="#004F81"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#4aa5d4" />
            <corners
                android:radius="7dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Try This试试这个

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_UP) {
                button.setBackgroundColor(Color.RED);
            } else if(event.getAction() == MotionEvent.ACTION_DOWN) {
                button.setBackgroundColor(Color.BLUE);
            }
            return false;
        }

    });

Refer this,参考这个,

boolean check = false;
Button backward_img;
Button backward_img1;
backward_img = (Button) findViewById(R.id.bars_footer_backward);
backward_img1 = (Button) findViewById(R.id.bars_footer_backward1);
backward_img.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        check = true;
        backward_img.setBackgroundColor(Color.BLUE);
    }
});

if (check == true) {
    backward_img1.setBackgroundColor(Color.RED);
    backward_img.setBackgroundColor(Color.BLUE);
}
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- default -->
    <item
        android:state_pressed="false"
        android:state_focused="false">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#00a3e2" />

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

        </shape>
    </item>

    <!-- button focused -->
    <item
        android:state_pressed="false"
        android:state_focused="true">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#5a97f5" />

            <padding
                android:bottom="5dp"
                android:left="10dp"
                android:right="10dp"
                android:top="5dp" />
        </shape></item>

    <!-- button pressed -->
    <item
        android:state_pressed="true"
        android:state_focused="false">
        <shape
            android:innerRadiusRatio="1"
            android:shape="rectangle" >
            <solid android:color="#478df9"/>
            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
        </shape></item>
</selector>

If you want to change the backgorund image or color of the button when it is pressed, then just copy this code and paste in your project at exact location described below.如果您想在按下按钮时更改按钮的背景图像或颜色,则只需复制此代码并将其粘贴到您的项目中,如下所述。

      <!-- Create new xml file like mybtn_layout.xml file in drawable -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/pressed" /> <!--pressed --> 
<item android:drawable="@drawable/normal" /> <!-- Normal -->
</selector>
  <!-- Now this file should be in a drawable folder and use this 
  single line code in    button code to get all the properties of this xml file -->

    <Button
      android:id="@+id/street_btn"
      android:layout_width="wrap_content"
      android:background="@drawable/layout_a" > <!-- your required code -->
    </Button>

1-make 1 shape for Button right click on drawable nd new drawable resource file . 1-为按钮制作1个形状,右键单击可绘制和新的可绘制资源文件。 change Root element to shape and make your shape.将根元素更改为形状并制作您的形状。

enter image description here在此处输入图片说明

2-now make 1 copy from your shape and change name and change solid color. 2-现在从您的形状制作 1 个副本并更改名称并更改纯色。 enter image description here在此处输入图片说明

3-right click on drawable and new drawable resource file just set root element to selector. 3 右键单击​​可绘制和新的可绘制资源文件,只需将根元素设置为选择器。

go to file and set "state_pressed"转到文件并设置“state_pressed”

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

<item android:state_pressed="true"android:drawable="@drawable/YourShape1"/>
<item android:state_pressed="false" android:drawable="@drawable/YourShape2"/>

</selector>

4-the end go to xml layout and set your Button background "your selector" 4-最后转到xml布局并设置您的按钮背景“您的选择器”

(sorry for my english weak) (抱歉我的英语不好)

Try this......试试这个……

First create an xml file named button_pressed.xml These are it's contents.首先创建一个名为 button_pressed.xml 的 xml 文件,这些是它的内容。

<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" 
          android:state_pressed="false" 
          android:drawable="@drawable/icon_1" />
    <item android:state_focused="true" 
          android:state_pressed="true"
          android:drawable="@drawable/icon_1_press" />
    <item android:state_focused="false" 
          android:state_pressed="true"
            android:drawable="@drawable/icon_1_press" />
    <item android:drawable="@drawable/icon_1" />
</selector>

Noe try this on your button.不,在你的按钮上试试这个。

int imgID = getResources().getIdentifier("button_pressed", "drawable", getApplication().getPackageName());
button.setImageResource(imgID);

button_pressed.xml should be in the drawable folder. button_pressed.xml 应该在 drawable 文件夹中。 icon_1_press and icon_1 are two images for button press and normal focus. icon_1_press 和 icon_1 是按钮按下和正常焦点的两个图像。

you can try this code to solve your problem你可以试试这个代码来解决你的问题

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

write this code in your drawable make a new resource and name it what you want and then write the name of this drwable in the button same as we refer to image src in android在你的 drawable 中编写这段代码创建一个新资源并命名它你想要什么,然后在按钮中写入这个 drwable 的名称,就像我们在 android 中引用图像 src 一样

I am use this code (with ripple effect):我正在使用此代码(具有涟漪效应):

<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/color_gray">
<item android:id="@android:id/mask">
    <color android:color="@color/color_gray" />
</item></ripple>
public void onPressed(Button button, int drawable) {
            if (!isPressed) {
                button.setBackgroundResource(R.drawable.bg_circle);
                isPressed = true;
            } else {
                button.setBackgroundResource(drawable);
                isPressed = false;
            }
        }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.circle1:
                onPressed(circle1, R.drawable.bg_circle_gradient);
                break;
            case R.id.circle2:
                onPressed(circle2, R.drawable.bg_circle2_gradient);
                break;
            case R.id.circle3:
                onPressed(circle3, R.drawable.bg_circle_gradient3);
                break;
            case R.id.circle4:
                onPressed(circle4, R.drawable.bg_circle4_gradient);
                break;
            case R.id.circle5:
                onPressed(circle5, R.drawable.bg_circle5_gradient);
                break;
            case R.id.circle6:
                onPressed(circle6, R.drawable.bg_circle_gradient);
                break;
            case R.id.circle7:
                onPressed(circle7, R.drawable.bg_circle4_gradient);
                break;

        }

please try this, in this code im trying to change the background of button on button click this works fine.请试试这个,在这段代码中,我试图改变按钮上按钮的背景点击这工作正常。

To deal properly for how long you want to have your button stay in your other color I would advise this version:为了正确处理你想让按钮保持其他颜色的时间,我建议这个版本:

button.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        button.setBackground(getResources().getDrawable(R.drawable.on_click_drawable));
                        break;
                    case MotionEvent.ACTION_UP:
                        new java.util.Timer().schedule(
                                new java.util.TimerTask() {
                                    @Override
                                    public void run() {
                                        ((Activity) (getContext())).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                button.setBackground(getResources().getDrawable(R.drawable.not_clicked_drawable));
                                            }
                                        });
                                    }
                                }, BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION);
                        break;
                    default:
                }
                return false;
            }
        });

BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION indicates after how much time [ms] the button will reset to the previous state (however you might want to use some boolean to check that the button hadn't been used in between, depending on what you want to achieve...). BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION 表示按钮将在多长时间 [ms] 后重置为以前的状态(但是,您可能想使用一些布尔值来检查按钮之间是否未被使用过,这取决于您想要实现的目标...) .

Even using some of the comments above this took way longer to work out that should be necessary.即使使用上面的一些评论,这也需要更长的时间来解决这应该是必要的。 Hopefully this example helps someone else.希望这个例子可以帮助其他人。

Create a radio_button.xml in the drawable directory.在 drawable 目录中创建一个 radio_button.xml。

    <?xml version="1.0" encoding="utf-8"?>

<!-- An element which allows two drawable items to be listed.-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/radio_button_checked" /> <!--pressed -->
    <item android:drawable="@drawable/radio_button_unchecked" /> <!-- Normal -->
</selector>

Then in the xml for the fragment should look something like然后在片段的 xml 中应该看起来像

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

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

<RadioButton

    android:id="@+id/radioButton1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_weight="1"
    android:button="@drawable/radio_button"
    android:paddingLeft="10dp" />        
<RadioButton
    android:id="@+id/radioButton2"
    android:layout_marginLeft="10dp"
    android:paddingLeft="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:button="@drawable/radio_button" />

</RadioGroup>
    </LinearLayout>
</layout>

Just add 1 line in XML for the click item只需在 XML 中为点击项目添加 1 行

android:background="?android:attr/selectableItemBackground" android:background="?android:attr/selectableItemBackground"

hai the most easiest way is this: hai 最简单的方法是这样的:

add this code to mainactivity.java将此代码添加到 mainactivity.java

public void start(View view) {

  stop.setBackgroundResource(R.color.red);
 start.setBackgroundResource(R.color.yellow);
}

public void stop(View view) {
stop.setBackgroundResource(R.color.yellow);
start.setBackgroundResource(R.color.red);
}

and then in your activity main然后在您的活动主要

    <button android:id="@+id/start" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="start" android:text="Click">

</button><button android:id="@+id/stop" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="stop" android:text="Click">

or follow along this tutorial或按照本教程进行操作

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

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