简体   繁体   中英

How do I save the content view of my activity?

Alright so in my activity i changed my content view from one to another as you can see. so i was wondering how to save the content view that was there last when my activity was closed.

 public class Levels extends Activity{

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
    setContentView(R.layout.levels);

    final EditText anstext1 = (EditText) findViewById(R.id.anstext1);
    Button button1 = (Button) findViewById(R.id.button1);

    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {   
             String result = anstext1.getText().toString();
             if(result.equals("they"))
                 setContentView(R.layout.social);
             else 
               Toast.makeText(getApplicationContext(), "Wrong", Toast.LENGTH_LONG).show();
        }
    });
    }
}

setContentView

You should call this method only once in the Activity lifecycle.

Saving State

Most of the time you will save your models using onSaveInstanceState and restore them using the bundles generated from that method. Activity, Fragment and Views have these kind of methods build in.

Persisting state

If you are required to use the data for a longer period than the current app lifecycle you can use one of the following mechanisms:

  1. SharedPreferences
  2. SQL-lite DB
  3. File I/O
  1. Create a variable that has the type of R.layout.levels. Assuming R.layout.levels is a RelativeLayout: RelativeLayout rl;

  2. Initialize it like this: rl = (RelativeLayout) getLayoutInflater().inflate(R.layout.levels,null);

  3. setContentView (rl);

If you want to save the variable for when the activity is destroyed you can put it in a custom Application class and retrieve it from there. You find here how to do it at "maintaining global state" : http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android

I don't know if it is good or bad to do this, but it could be a solution for what you're asking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM