应用程序运行两次时显示相同的图像

时间:2015-04-03 12:09:00

标签: java android

我正在构建一个小型的Android应用程序,我是android新手。 我有两个图像,一个是花,另一个是动物。 当我运行我的应用程序时,将显示第一朵花,当我按下花时,它应该切换到动物。现在将显示动物图像。如果我回去再次运行我的应用程序,我将显示一朵花的图像。 但我希望只显示动物图像。 一旦我回去再跑,什么都不应该改变。

我怎么能这样做,java中的代码会有所帮助 在此先感谢

2 个答案:

答案 0 :(得分:1)

修改 您可以在此处查看活动生命周期: http://developer.android.com/reference/android/app/Activity.html

当您转到主屏幕时,将调用onPause()方法。 当您恢复活动并且它具有焦点(可见)时,将调用onResume()方法。 您的成员类属性不会被修改。如果将属性声明为" TRUE"并且你在代码中将它修改为" FALSE",如果你恢复应用程序,它总是#34; FALSE"。

Hovewer,你必须要小心! 当您的应用程序没有焦点时(即您可以在多任务管理器中看到它),系统可以销毁活动以释放内存。如果您没有保存活动状态,则会将其重新创建为默认状态。

这就是你应该使用它的原因:http://developer.android.com/training/basics/activity-lifecycle/recreating.html

你必须保存一个布尔值来知道它是第一个还是第二个图像,并在onRestoreInstanceState()中恢复好图像。

这样的事情应该有用。

//change this to false when you change the image
public boolean isFirstImage = true;
public ImageView image;

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putBoolean("isFirstImage", isFirstImage);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    image = (ImageView) findViewById(R.id.myview);
    image.setDrawable(getResources().getDrawable(R.drawable.flower));
    image.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isFirstImage) {
                image.setDrawable(getResources().getDrawable(R.drawable.flower));
                isFirstImage = false;
            } else {
                image.setDrawable(getResources().getDrawable(R.drawable.animal));
                isFirstImage = true;
            }
        }
    }
}

public void onResume() {
    if (isFirstImage) {
        image.setDrawable(getResources().getDrawable(R.drawable.flower));
    } else {
        image.setDrawable(getResources().getDrawable(R.drawable.animal));
    }
}

public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);

    // Restore state members from saved instance
    isFisrtImage = savedInstanceState.getBoolean("isFirstImage");


    if (isFirstImage) {
        image.setDrawable(getResources().getDrawable(R.drawable.flower));
    } else {
        image.setDrawable(getResources().getDrawable(R.drawable.animal));
    }
}

答案 1 :(得分:0)

您可以使用SharedPreferences来保存图像的状态,方法是保存一些布尔值,每当您返回活动时只为该值并根据您设置图像。

点击链接http://developer.android.com/reference/android/content/SharedPreferences.html