2013-05-16 34 views
0

我的onCreate方法設置內容視圖,並設置了一個圖像按鈕:Android:我如何參考主要活動之外的佈局項目?

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ImageButton mGetClickTime = (ImageButton) findViewById(R.id.clicker); 

}

但我希望創建一個改變的ImageButton背景的方法:

public void mUpdateBackground() { 
if (backgroundPic) { 
    randomImageId = R.drawable.bg1; 
} 
else { 
    randomImageId = R.drawable.bg0; 
} 
mGetClickTime.setImageResource(randomImageId); 
} 

問題是,mUpdateBackground方法不知道佈局。如果我在方法中聲明佈局,它會重置MainActivity中編程方式所做的所有更改。

任何想法如何我可以解決這個問題?

回答

3

您需要將ImageButton聲明移至您的活動範圍,而不是您的onCreate()方法範圍。嘗試像這樣:

public class YourActivity extends Activity{ 
    ImageButton mGetClickTime; 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     mGetClickTime = (ImageButton) findViewById(R.id.clicker); 
    } 


    public void mUpdateBackground() { 
     if (backgroundPic) { 
      randomImageId = R.drawable.bg1; 
     } 
     else { 
      randomImageId = R.drawable.bg0; 
     } 
     mGetClickTime.setImageResource(randomImageId); 
    } 
} 
+0

感謝您的幫助。我試過了,但mUpdateBackground方法中的mGetClickTime顯示爲空,即使onCreate中的一個顯示爲正確分配。有任何想法嗎? –

+0

已經明白了。問題是我忘了更改ImageButton mGetClickTime =(ImageButton)findViewById(R.id.clicker);到mGetClickTime =(ImageButton)findViewById(R.id.clicker);非常感謝 –

4

的mUpdateBackground方法不知道的佈局

我要翻譯這意味着:

的mUpdateBackground方法不知道有關的ImageButton

如果這是正確的,請將ImageButton mGetClickTime作爲您活動的數據成員,而不是本地變量在onCreate()之內,並且mUpdateBackground()是該同一活動的一種方法。

+0

感謝您的幫助。我試過了,但mUpdateBackground方法中的mGetClickTime顯示爲空,即使onCreate中的一個顯示爲正確分配。有任何想法嗎? –

+0

對不起,我剛剛重讀。你的意思是在類定義之後但在onCreate之前設置ImageButton mGetClickTime?這是否使它成爲一個字段變量? –

+1

我懂了。問題是我忘了更改\t \t ImageButton mGetClickTime =(ImageButton)findViewById(R.id.clicker); 至\t \t mGetClickTime =(ImageButton)findViewById(R.id.clicker); –