单击后在按钮中更改图像?

时间:2010-04-14 04:50:36

标签: xml android button

使用多个按钮在Android中创建游戏,以显示可绘制文件夹中的图像。我想在单击按钮后将按钮更改为其他图像。这是按钮代码:

    <Button android:id="@+id/b36"
    android:background="@drawable/black"
    android:layout_width="45px"
    android:layout_height="45px"
    />  

我找不到任何关于如何更改按钮的实际图像的信息。您可以使用java文件中的以下代码更改按钮的颜色:

b36.setBackgroundColor(0xAA00AA00);

3 个答案:

答案 0 :(得分:3)

你必须使用图像视图作为按钮。将图像视图的背景设置为xml文件。在资源drawable中我们可以使用xml文件。检查Api demos drawable文件夹。该xml文件包含此代码。

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

<item android:state_pressed="false"
    android:drawable="@drawable/button _image_in_normal_state" />

<item android:state_pressed="true"
    android:drawable="@drawable/button _image_in_pressed_state" />

</selector>

并将它们放在res / drawable文件夹中的图像文件中。你可以实现你想要的目标吗?

也请参阅此link

答案 1 :(得分:1)

也许你想使用ImageButton。然后你可以调用像button.setImageDrawable()这样的方法。

答案 2 :(得分:0)

按下后更改按钮背景的快速示例。

在你的活动的创造中:

   btn_36= (Button) findViewById(R.id.b36);
   btn_36.setOnClickListener(new OnClickListener() {
       public void onClick(View v) {
           btn_36.setBackgroundResource(R.drawable.white);
       }
   });
相关问题