2013-05-16 35 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); –