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


81

我正在开发Android应用程序。我想将4个按钮水平放置在屏幕底部。在这4个按钮中,有2个按钮上面有图像。按钮的边框应为黑色,边框应尽可能细。当我单击按钮时,我希望按钮的背景应更改为蓝色而不更改边框的颜色,并且应将其保留一段时间。如何在Android中实现此方案?


如何更改按钮单击上的矢量绘制路径的颜色的可能重复项 我将其标记为重复项,您可以在此处检查我的答案:stackoverflow.com/a/55205149/3763032
mochadwi

Answers:


127

一种方法是在中创建一个类似XML文件的文件,该文件drawable名为what.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>

bgaltbgnorm在绘制PNG图像。

如果您在活动中以编程方式创建按钮,则可以使用以下方法设置背景:

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

如果使用XML设置按钮的样式,则应执行以下操作:

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

最后是教程链接。希望这可以帮助。


16
如果要避免使用图像,也可以用颜色定义替换XML文件中的那些可绘制对象。
haseman

7
@ jshin47一次反复的试验和错误。我现在已经写了两本关于Android开发的书:-)
haseman 2012年

@haseman-您可以张贴这两本书的链接还是可以通过brk0018@gmail.com与我分享。很高兴经历这些并学习得更好
Ramakishna Balla 2014年

1
如果只是着色而不是图像怎么办?
Kala J

@KalaJ您是否找到了解决方案?
Prafulla Kumar Sahu

74

将此代码保存在具有“ bg_button.xml”的drawable文件夹中,并调用“ @ drawable / bg_button”作为xml中按钮的背景:

<?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>

2
谢谢您,使用样式可以减少应用程序的大小。不要使用drawable的好主意
Rahul Mandaliya 2014年

另一方面,基于xml向量的可绘制对象通常在性能上比图像差,尤其是在较旧的设备上。不要过早优化,但也要记住这一点。
Przemyslaw Jablonski

10

试试这个

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

    });

9

引用这个

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

2
这将永久设置BG,即,如果用户单击“后退”按钮,则背景将为红色。
方法

@methode:好的,请参考新答案,我已经更正了旧答案
Sankar Ganesh PMP 2010年

8
<?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>

6

如果要在按下按钮时更改backgorund图像或按钮的颜色,则只需复制此代码并将其粘贴到项目中的下面所述的确切位置。

      <!-- 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>

4

试试这个......

首先创建一个名为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>

否,请按一下按钮。

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

button_pressed.xml应该在drawable文件夹中。icon_1_press和icon_1是按钮按下和正常对焦的两个图像。


2

右键单击drawable和new drawable资源文件,为Button制作1个形状1的形状。更改Root元素的形状并制作形状。

在此处输入图片说明

2-现在从您的形状制作1个副本,并更改​​名称和更改纯色。 在此处输入图片说明

3右键单击drawable和new drawable资源文件,只需将根元素设置为选择器即可。

转到文件并设置“ 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-最后转到xml布局,然后将Button背景设置为“您的选择器”

(对不起,我的英语能力很弱)


1

我正在使用此代码(具有涟漪效应):

<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>

1

您可以尝试使用此代码来解决您的问题

<?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>

在您的drawable中编写此代码,制作一个新资源,并按您的需要命名,然后在按钮中编写此drwable的名称,就像我们在android中引用image src一样


1
您好先生@lmo我已经对这个问题做了一些解释。
Mudassir Khan

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

        }

请尝试此操作,在此代码中,im试图更改按钮上单击按钮的背景,效果很好。


0

为了正确处理您希望按钮以其他颜色停留多长时间,我建议您使用以下版本:

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指示在多少时间[ms]后按钮将重置为之前的状态(但是您可能希望使用一些布尔值来检查两次按钮之间是否未使用该按钮,具体取决于您要实现的目标...) 。


0

即使使用上面的一些评论,这也花费了更长的时间来解决这是必要的。希望这个例子可以帮助其他人。

在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>

然后在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>

-1

hai最简单的方法是这样的:

将此代码添加到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);
}

然后在您的活动主

    <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">

或按照本教程进行操作

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.