esoni
esoni

Reputation: 1362

how to save configuration layout android

I have an application where the main layout is loaded from xml file.

The layout loaded is :

A relative layout with 5 button. When user click on the button appear a menu, where he can choose a type of view. After choosing view, button will invisible and appears chosen view.

After restarting the application , system load default layout ( relative layout with 5 button). I want that when the application restart the system load the last selected layout.

Is it possible to do?

Upvotes: 2

Views: 581

Answers (1)

Aaron Fujimoto
Aaron Fujimoto

Reputation: 321

You should be able to do this by using Shared Preferences in Android: http://developer.android.com/guide/topics/data/data-storage.html#pref

You may store a boolean value to track the state of the layout (whether it is the RelativeLayout with 5 Buttons, or the View chosen state with 4 Buttons). This way when you load the activity, you can first check this flag to determine which layout you want to load. You can also use the preference such that you do not need to initialize this flag variable, but instead you can use a default value.

public class MyActivity extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";
    public enum ViewState {
        NO_CLICK, VIEW_A, VIEW_B, ...
    };

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       int currentView = settings.getInt("viewClicked", NO_CLICK);

       switch(currentView)
       {
           case VIEW_A: // Load the view if button A was clicked
               loadViewA();
               break;
           case VIEW_B: // Load the view if button B was clicked
               loadViewB();
               break;
           ...
           case NO_CLICK: // Load the RelativeLayout with 5 Buttons
           default:
               loadDefaultView();
               break;
       }
    }

And in your OnClickListener for the button A:

public void onClick(View v) {

  ...

  // Get the settings
  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putInt("viewClicked", VIEW_A);

  // Commit the edits!
  editor.commit();

  // Load the view
  loadViewA();
}

The other onClick() method for the other buttons could be implemented similarly.

Edit: Updated to use an integer rather than a boolean

Upvotes: 2

Related Questions