Perfect_Comment
Perfect_Comment

Reputation: 195

How to persist the state of switches within a List view

This is my first attempt at using list views and i have created a list view containing switches. Whenever i navigate away from the activity the state of the switches reset back to their default value. The list view contains 4 switches and many of the answers i have came across deal with a problem of switches resetting their state when they are out of view.

I have thought about creating an array and storing the state of each switch and then loading the state when the user navigates back to the activity. Does anyone have any advice as how to best achieve this?

public View getView(final int position, View convertView, ViewGroup    parent) {
    View view;

    if (convertView == null) {
        view = mInflater.inflate(R.layout.options_list_item, parent,   false);
    } else {
        view = convertView;
    }

    symbols m1 = getItem(position);

    Switch optionsSwitch = (Switch) view.findViewById(R.id.switch2);

    optionsSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked && position == 0) {
                state = true;
            } else {
                state = false;
            }
        }
    });

    return view;
} 

Upvotes: 1

Views: 38

Answers (1)

Elltz
Elltz

Reputation: 10859

There is no best way to achieve it your thoughts to it is great, infact you are the best judge to know what best fit your design model and app design etc,

but you could always persist data through the always talked about sharedpreferences, to disk by yourself or in heap memory as you stated.

Hope it helps

Upvotes: 1

Related Questions