2010-04-14 92 views
2

使用多個按鈕在Android中創建遊戲以顯示可繪製文件夾中的圖像。我想在單擊按鈕後將按鈕更改爲不同的圖像。這裏是按鈕代碼:單擊後在按鈕中更改圖像?

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

我找不到任何關於如何更改按鈕的實際圖像。您可以通過使用Java文件下面的代碼更改按鈕的顏色:

b36.setBackgroundColor(0xAA00AA00); 

回答

1

也許你想使用一個ImageButton。然後你可以調用像button.setImageDrawable()等這樣的方法。

3

你必須使用圖像視圖作爲按鈕。將圖像視圖的背景設置爲xml文件。在繪製資源時我們可以使用xml文件。檢查Api demos可繪製文件夾。該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

+0

這幫助了我很多,但事實證明,你可以用這個按鈕,包括因爲它是最看法。您只需將圖像背景設置爲該資源文件。很好的答案 – mtmurdock 2010-10-01 17:20:06

0

快速例子。

在你活動的OnCreate:

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