Android: Why Spinner.setSelection does not show correct value in the UI?

16 Views Asked by At

I have a Fragment (A) with a Spinner containing a list of years. From this fragment I can open Fragment (B) to get information about the year selected in the Spinner.

Moreover, from Fragment B I can move a year up or down using buttons. However, when I press back to return to Fragment A, the Spinner shows the original year selected, instead of last year queried by the user.

In order to update the Spinner with this year, I send the year to Fragment A with:

        Bundle lastYear = new Bundle();
        lastYear.putString("year", temp);
        this.getParentFragmentManager().setFragmentResult("lastYear", lastYear);

In Fragment A, I get the result from Fragment B and store it in yearSpinner:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getParentFragmentManager().setFragmentResultListener("lastYear", this, 
            new FragmentResultListener() {
        @Override
        public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
            yearSpinner = result.getString("year");
        }
    });
}

Then, I try to change the Spinner selected item using yearSpinner:

public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    this.spinner = view.findViewById(R.id.temporada_spinner);
    this.spinner.setAdapter(this.adaptadorSpinner);
    
    if (this.yearSpinner!= null) {
        Log.d("testing", "yearSpinner:" + yearSpinner);
        Log.d("testing", "position:" + this.adaptadorSpinner.getPosition(this.yearSpinner));
        this.spinner.setSelection(this.adaptadorSpinner.getPosition(this.yearSpinner));
        Log.d("testing", "selected:" + this.spinner.getSelectedItem().toString());
    } 
}

It works. When I check the logs, all information is correct. Both the value and the item selected are correct. Despite of that, UI shows the original selected year, instead the one in yearSpinner. Why?

The problem doesn't seem to be where the code is placed, as if I do this, it works:

    this.yearSpinner = "2020/21";
    if (this.yearSpinner != null) {
        this.spinner.setSelection(this.adaptadorSpinner.getPosition(this.yearSpinner));
    }

I have tried using this.spinner.setSelection(this.adaptadorSpinner.getPosition(this.yearSpinner), true) and this.spinner.setSelection(this.adaptadorSpinner.getPosition(this.yearSpinner), true), but didn't work.

Below code worked for me, but I do not like the result, as the selected item changes when the view is already visible:

    spinner.post(new Runnable() {        
        public void run() {
            spinner.setSelection(this.adaptadorSpinner.getPosition(this.yearSpinner));
        }
    });
0

There are 0 best solutions below