我有一个ImageButton
并且我希望它的形象在每次被调用onResume()
时都会改变。onCreate()
我有一个更改图像的方法,称为mUpdateBackground
,但我无法确定如何构造层次结构,以便可以从和调用mUpdateBackground
, (包含) 。ImageButton
onResume()
onCreate()
如果backgroundPic
为真,则随机选择图像,如果为假,则R.drawable.bg0
使用图像代替。
有一个单独的设置活动来管理backgroundPic
变量是设置为真还是假。
到目前为止,这是我的代码:
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", "backgroundPic: "+randomImageId);
43 }
44 mGetClickTime = (ImageButton) findViewById(R.id.clicker);
45 mGetClickTime.setImageResource(randomImageId);
46 }
我遇到的问题是,如果我取消注释第 11 行,我会得到一个NullPointerException。有没有更好的方法来组织这段代码?