Behavior of Spinners with Bank Data in the Life Cycle

0

I have 3 Spinners inside a Fragment, the problem I'm having is when I spin the Tablet screen and the screen rebuilds, so the Spinners are reset.

The first Spinner comes from the bank, depending on the selection of the first Spinner the second is filled and so is the third Spinner when I choose the second.

I already deal with the data, because when selecting the item it already saves in the bank, however, when I turn the screen I have the problems described above, follows a method that I use to show the saved item even leaving the screen ...

public void setSpinnerSelection(Spinner spinner, Adapter adapter, String text) {
    for (int i = 0; i < adapter.getCount(); i++) {
        String comparar = adapter.getItem(i).toString();
        if (comparar.equals(text)) {
            spinner.setSelection(i);
        }
    }
}

I noticed something strange too, is it common when the fragment is rebuilt, does it perform what it has inside this Spinner method? "setOnItemSelectedListener", I realized that this is exactly the "bottleneck".

In short, I wanted to know a clever way to work with the fragment lifecycle.

    
asked by anonymous 07.10.2015 / 19:13

2 answers

0

I found out how to solve this problem ...

Just use Spinner's setOnTouchListener ...

    spinner.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // Marca como selecionado.
            chave = true;
            return false;
        }
    });

After you make the TRUE key, just use it ...

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (chave) {
            //Instrução...

            }
    }

In this way, even if the Fragment or Activity reconstructs, the values remain ...

    
07.10.2015 / 20:12
1

You must override the onSaveInstanceState method and save the indexes of the selected items of each spinner . Later, when fragment is recreated, you can get those values through the Bundle passed to the onActivityCreated method.

It will be anything like this:

@Override
public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
    bundle.putLong("indice1", spinner1.getSelectedItemPosition());
    bundle.putLong("indice2", spinner2.getSelectedItemPosition());
    bundle.putLong("indice3", spinner3.getSelectedItemPosition());

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        //Restore the fragment's state
        int index1 = savedInstanceState.getLong("indice1");
        int index2 = savedInstanceState.getLong("indice2");
        int index3 = savedInstanceState.getLong("indice3");

    }
}
    
07.10.2015 / 20:21