2011-07-17 169 views
1

我的應用有一個背景,應該在某些事件發生後更改。那麼,我該怎麼做呢?如何更改Android應用程序中的背景圖像?

的main.xml:

<AbsoluteLayout 
android:id="@+id/widget0" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:background="@drawable/bg"> 

有背景應改爲:

if(a<b) *change background to bg2.jpg goes here* 

幫助,請與遺憾,我的英語

+0

強烈不建議使用AbsoluteLayout。 – PravinCG

回答

2

我看你使用絕對佈局。所以只需實例化新的AbsoluteLayout對象。

AbsoluteLayout al = (AbsoluteLayout) findViewById(R.id.widget0); 
//This function will change background drawable, so place it where you want. 
al.setBackgroundDrawable(yourDrawableID); 

順便問一下,你也可以做

al.setBackgroundResource(resourceID); 

與RESOURCEID應該導航到繪製ID和設置爲0,如果你想刪除的背景。

+0

不贊成使用AbsoluteLayout類型。我該怎麼做才能避免這個錯誤? – Alexander

+1

已棄用它以確保Android應用程序與許多屏幕分辨率兼容。如果您確實想要使用AbsoluteLayout,請確保兼容。爲什麼你需要AbsoluteLayout?如果您需要將控件放置在特定位置,則可以在RelativeLayout中執行此操作。 –

+0

謝謝,它適用於我。 – Alexander

0

其簡單,android:background="@drawable/YourImage"

+0

您應該將代碼寫入XML文件的佈局標記中。 – anilbey

相關問題