1

With android studio I'm working on a button and i want that every time i click it THE BACKGROUND OF THE BUTTON change and when i do not , there is another background. I don't have a clue of how to do that, can you help me?

4

2 回答 2

2

Xml 布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/main" >
<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Change"
    android:onClick="changeBack" />

</LinearLayout>

将此代码添加到您的活动中

public boolean firstImage = true;
public void changeBack(View view)
{
    if (firstImage)
        ((LinearLayout)findViewById(R.id.main)).setBackgroundResource(R.drawable.secondimage);
    else
        ((LinearLayout)findViewById(R.id.main)).setBackgroundResource(R.drawable.firstimage);
    firstImage = !firstImage;
}
于 2013-09-28T18:08:52.200 回答
1

/res/drawable在项目的文件夹中创建一个 xml 文件。drawable如果/res 目录中不存在名为的文件夹,请创建它。例如,命名 xml 文件button_bg.xml

复制并粘贴以下代码button_bg.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true" android:drawable="@drawable/drawable_when_pressed" />
  <item android:drawable="@drawable/default_drawable" />
</selector>

drawable_when_pressed并且default_drawable是您想要用作按钮背景的可绘制资源。按下按钮时,按钮的背景将为drawable_when_pressed. 否则,它将是default_drawable

您将此可绘制对象 (button_bg.xml) 设置为按钮的背景。以下是如何使用它:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_bg"
    android:text="Button" />

这是可绘制状态列表的一种非常基本的形式。您可以在此处阅读更多信息:链接

于 2013-09-28T21:35:29.013 回答