2012-11-29 72 views
4

我有一個背景定義爲可繪製的佈局,我想在某些情況下將其更改爲另一個。我如何獲得當前背景的標識以瞭解它是什麼?獲取視圖的當前背景ID

+0

你應該設置'id'佈局,成爲電流,然後聲明它由'findviewbyid' incode和那麼通過這個聲明你將能夠改變背景 – deadfish

+0

這個問題很有趣,但是我沒有看到用例? – njzk2

回答

3

你好你可以試試這個例子,

btnNew =(Button)findViewById(R.id.newButton); 

// compare newlist 
if(newButton.getBackground()!=(findViewById(R.id.imgAdd)).getBackground()) 
{ 
    btnNew.setBackgroundResource(R.drawable.imgDelete); 
} 
+0

好吧,我真的看到你的評論之後,我編輯:) thanx – Talha

+1

-1 for'findViewById(R.drawable.imgAdd)'(通過id找到一個可繪製的ref,它返回null。 – njzk2

+1

我寫它只是在這裏,而不使用編輯器。無論如何,我編輯我的答案。Thanx爲你的-1 :) – Talha

1

您可以通過這種方式嘗試。

將id分配給您想根據條件更改背景的佈局。做這樣的

  linear1 = (LinearLayout) findViewById(R.id.bg_l_l); 

     if(condition==true) 
     { 
      linear1.setBackgroundDrawable(R.drawable.sample_thumb_0); 
     } 
     else if (condition2==true) 
     { 
      linear1.setBackgroundDrawable(R.drawable.sample_thumb_1); 
     } 
     else 
     { 
      linear1.setBackgroundDrawable(R.drawable.sample_thumb_2); 
     } 
+1

什麼是條件,他想比較drawables – Pragnani

+0

作爲提問者告訴他,他想要根據條件進行更改。所以他會決定應該是什麼條件。 –

+0

他想比較drawables,這就是爲什麼他問條件 – Pragnani

1

你可以簡單地得到整個Drawable通過Drawable beforeClickDrawalbe=view.getBackground();

並做更改您的視圖的背景:如果你想將其設置回view.setBackgroundDrawable(getResources().getDrawable(R.drawable.YOUR_DRAWABLE));

,然後最初的背景你不需要ID 因爲你有整個Drawable所以做: view.setBackgroundDrawable(beforeClickDrawalbe));

就這樣!

5

這可能是一個很古老的問題,但爲了以防萬一,如果人們還在尋找它:

if(yourView.getBackground().getConstantState().equals(
    getResources().getDrawable(R.drawable.yourdrawable).getConstantState()){ 

    //do something if this is the correct drawable 
} 
+0

你真棒感謝很多.. !!! :) –