我有一个主要活动,ImageButton
每次点击都会更改图像。
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
static ImageButton mGetClickTime;
mGetClickTime.setOnClickListener(new View.OnClickListener() {
mUpdateBackground();
}
}
}
public static void mUpdateBackground() {
int[] imageIds = {
R.drawable.bg1,
R.drawable.bg2,
R.drawable.bg3,
R.drawable.bg4,
};
Random generator = new Random();
randomImageId = imageIds[generator.nextInt(imageIds.length)];
mGetClickTime.setImageResource(randomImageId);
}
这工作正常,直到单击菜单按钮并访问另一个活动
public class settings extends MainActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
}
}
当按下菜单或返回按钮时,我们返回到主活动。但是一旦发生这种情况,ImageButton
每次点击都不再更新图像。其他一切仍然有效,包括每次点击时更新的文本框。
我究竟做错了什么?
编辑
感谢你的帮助。目前,它似乎在我从子活动返回后继续工作。(万岁!)
但是现在当从或从其他活动调用时,我无法让该mUpdateBackground
方法工作。onResume()
这是我所在的位置:
1 public class MainActivity extends Activity {
2 public static ImageButton mGetClickTime;
3 @Override
4 protected void onResume() {
5 super.onResume();
6 //Get shared preferences
7 mSharedPreferences = getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE);
8 dp = mSharedPreferences.getInt("DecimalPlaces", 0);
9 length_setting = mSharedPreferences.getInt("MSSelector", 1);
10 backgroundPic = mSharedPreferences.getBoolean("BackgroundPic", true);
11 //mUpdateBackground();
12 }
12 @Override
13 protected void onCreate(Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15 setContentView(R.layout.activity_main);
16
17 //Get shared preferences
18 mSharedPreferences = getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE);
19 dp = mSharedPreferences.getInt("DecimalPlaces", 0);
20 length_setting = mSharedPreferences.getInt("MSSelector", 5);
21 mUpdateBackground();
22 mGetClickTime.setOnClickListener(new View.OnClickListener() {
23 mUpdateBackground();
24 }
25 }
26 }
27 public void mUpdateBackground() {
28 if (backgroundPic) {
29 int[] imageIds = {
30 R.drawable.bg1,
31 R.drawable.bg2,
32 R.drawable.bg3,
33 R.drawable.bg4,
34
35 };
36 Random generator = new Random();
37 randomImageId = imageIds[generator.nextInt(imageIds.length)];
38 Log.d("1", "backgroundPic: "+randomImageId);
39 }
40 else {
41 randomImageId = R.drawable.bg0;
42 Log.d("1", "backgroundPicCALLED: "+randomImageId);
43 }
44 mGetClickTime = (ImageButton) findViewById(R.id.clicker);
45 mGetClickTime.setImageResource(randomImageId);
46 }
我遇到的问题是,如果我取消注释第 11 行,我会得到一个NullPointerException
. 那可能是因为第mUpdateBackground()
27 行的方法不是static
吗?如果我做到了,static
那么在第 44 行我得到一个错误findViewById
,不能从类型中static
引用non-static
方法。我真的很难过。我显然没有正确遵循逻辑,但我已经检查了几次,我看不出它可能是什么。findViewById(int)
Activity