当单击/聚焦按钮时如何更改背景图像?

42

我想在按钮被点击或聚焦时更改其背景图片。

这是我的代码:

Button tiny = (Button)findViewById(R.id.tiny);
tiny.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Button tiny = (Button)findViewById(R.id.tiny);
        tiny.setBackgroundResource(R.drawable.a9p_09_11_00754);

        TextView txt = (TextView)findViewById(R.id.txt);
        txt.setText("!---- On click ----!");
    }
});

这段代码正确吗?它在事件中调用了一个按钮吗?

9个回答

92

你可以按照以下方式在xml文件中实现:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/your_imagename_while_focused"/>
<item android:state_pressed="true" android:drawable="@drawable/your_imagename_while_pressed" />
<item android:drawable="@drawable/image_name_while_notpressed" />  //means normal
</selector>

现在将这个XML文件保存在drawable文件夹中,并命名为abc.xml,然后按以下方式设置:

 Button tiny = (Button)findViewById(R.id.tiny);
 tiny.setBackgroundResource(R.drawable.abc);

希望它能对你有所帮助。:)


这个既不能在API 22上工作,也不能在API 16上工作。我尝试通过xml和编程两种方式实现。而@Chirag Raval提供的解决方案却可以运行。 - Jacob R
@JacobR,你说你两种方法都试过了,xml 和 programmatically?Chirag Raval 的实现仅使用 xml,那么为什么不起作用?我的实现是通过编程方式,它会起作用的,你一定做错了什么。 - Android Killer
xml: android:background="@drawable/selector_drawable" 编程方式:v.setBackgroundResource(R.drawable.selector_drawable) 尝试您和@Chirag Raval的答案,唯一的区别是选择器文件中的内容。我知道很久以前我使用了您的实现,并且它起作用了,而今天重用该代码却没有起作用,所以这可能与API有关。 - Jacob R
Android还会从drawable-xhdpi、drawable-xxhdpi等目录中选择适当大小的图像吗?还是说我们必须在每个drawable文件夹中放置一个选择器? - deanresin
@Matt,答案中已经提到了。 - Android Killer
显示剩余2条评论

58

实现起来非常简单。你只需要创建一个XML文件(选择器文件),并将其放置在res目录下的drawable文件夹中。然后在布局文件中将该XML文件设置为按钮的背景。

button_background_selector.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/your_hover_image" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/your_hover_image" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/your_hover_image"/>
    <item android:drawable="@drawable/your_simple_image" />
</selector>

现在将上述文件设置为按钮的背景。

<Button
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:textColor="@color/grey_text"
    android:background="@drawable/button_background_selector"/>

4
如果你尝试这种方法仍然遇到困难,请确保 <item android:drawable="@drawable/your_simple_image" /> 是在你的 selector 中最后一个元素。这是因为系统会循环遍历每个元素并选择与状态匹配的第一个元素。所以,如果这是第一个元素,它将匹配任何状态(按下、聚焦或正常),因此每次都会被选中 - 其他两个可绘制物(按下和聚焦)将永远不会显示。 - tytk
这应该是被接受的答案,它真的像魔法一样奏效了! - mohammedgqudah

9

抱歉,这是错误的。

要根据特定事件(聚焦、按下、正常)更改背景颜色/图像,您需要定义一个按钮选择器文件,并将其实现为按钮的背景。

例如:button_selector.xml(在drawable文件夹中定义此文件)

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:color="#000000" /> <!-- pressed -->
     <item android:state_focused="true"
           android:color="#000000" /> <!-- focused -->
     <item android:color="#FFFFFF" /> <!-- default -->
 </selector>

    <!-- IF you want image instead of color then write 
android:drawable="@drawable/your_image" inside the <item> tag -->

并应用它如下:

 <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:drawable="@drawable/button_selector.xml" />

当我提交我的答案时,我不知道他是否已经提交了它。 - Chirag
@Frankenstein,请检查一下我发布的时间。如果你看不到,那是我第一个回复的。 - Paresh Mayani
@Frankenstein 非常感兴趣。让我们在 chat.stackoverflow.com 内进行此类沟通。 - Paresh Mayani
我正在休闲聊天室或Android或Android讨论室等待。 - MKJParekh
这个问题要么过时了,要么是错误的。即使您使用颜色,也必须使用<item android:drawable="@color/my_color"...而不是android:color。 - Teo Inke
我该如何在Java类中不必通过编程方式创建XML文件来获取视图的不同状态。 - Matt

5

使用以下代码,在drawable文件夹中创建名为button的xml文件:

<?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/buutton_pressed" />
  <item 
     android:drawable="@drawable/button_image" />
</selector>

并且在按钮的XML文件中。
 android:background="@drawable/button"

3

我们可以采用两种方法来更改按钮的背景:

  1. In the button OnClick, just add this code:

     public void onClick(View v) {
         if(v == buttonName) {
            buttonName.setBackgroundDrawable
             (getResources().getDrawable(R.drawable.imageName_selected));
          }
    
           }
    

    2.Create button_background.xml in the drawable folder.(using xml)

    res -> drawable -> button_background.xml

       <?xml version="1.0" encoding="UTF-8"?>
        <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
             <item android:state_selected="true"
                   android:drawable="@drawable/tabs_selected" /> <!-- selected-->
             <item android:state_pressed="true"
                   android:drawable="@drawable/tabs_selected" /> <!-- pressed-->
             <item  android:drawable="@drawable/tabs_selected"/>
        </selector>
    

    Now set the above file in button's background file.

         <Button
               android:layout_width="fill_parent" 
               android:layout_height="wrap_content"
               android:background="@drawable/button_background"/>
    
                              (or)
    
             Button tiny = (Button)findViewById(R.id.tiny);
                   tiny.setBackgroundResource(R.drawable.abc);
    

    2nd method is better for setting the background fd button


谢谢@Ann,但是这个问题之前已经回答过了。 - Omid Nazifi

2
你只需要在布局文件中设置按钮的背景并将previous.xml文件作为其背景即可。
<Button
 android:id="@+id/button1"
 android:background="@drawable/previous"
 android:layout_width="200dp"
 android:layout_height="126dp"
 android:text="Hello" />

完成了。编辑以下是drawable目录中的previous.xml文件。

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

<item android:drawable="@drawable/onclick" android:state_selected="true"></item>
<item android:drawable="@drawable/onclick" android:state_pressed="true"></item>
<item android:drawable="@drawable/normal"></item>


这个问题以前已经被回答过了。 - Omid Nazifi

0

你也可以直接在item标签内创建形状,以便为视图添加更多细节,例如:

<?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="#81ba73" />
            <corners android:radius="6dp" />
        </shape>
        <ripple android:color="#c62828"/>
    </item>
    <item android:state_enabled="false">
        <shape>
            <solid android:color="#788e73" />
            <corners android:radius="6dp" />
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="#add8a3" />
            <corners android:radius="6dp" />
        </shape>
    </item>
</selector>

请注意,Android将从上到下循环遍历项目,因此,您必须将item无条件地放置在列表底部(以便它充当默认/回退)。

0
  1. 在drawable文件夹中创建一个名为play_pause.xml的文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true"
          android:drawable="@drawable/pause" />

    <item android:state_selected="false"
          android:drawable="@drawable/play" />
    <!-- default -->
</selector>
  1. 在 XML 文件中添加以下代码
 <ImageView
                android:id="@+id/iv_play"
                android:layout_width="@dimen/_50sdp"
                android:layout_height="@dimen/_50sdp"
                android:layout_centerInParent="true"
                android:layout_centerHorizontal="true"
                android:background="@drawable/pause_button"
                android:gravity="center"
                android:scaleType="fitXY" />
  • 在Java文件中添加以下代码
  • iv_play = (ImageView) findViewById(R.id.iv_play);
    iv_play.setSelected(false);
    

    并且还要添加这个

    iv_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    iv_play.setSelected(!iv_play.isSelected());
                    if (iv_play.isSelected()) {
                        ((GifDrawable) gif_1.getDrawable()).start();
                        ((GifDrawable) gif_2.getDrawable()).start();
                    } else {
                        iv_play.setSelected(false);
                        ((GifDrawable) gif_1.getDrawable()).stop();
                        ((GifDrawable) gif_2.getDrawable()).stop();
                    }
                }
            });
    

    0

    使用<androidx.appcompat.widget.AppCompatButton />替代'Button'


    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接