Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically setSelection of spinner, do not trigger OnItemSelectedListener

I have a activity that have many cascaded spinner and after select first one, second spinner initialize and fill data and after select item from second, third spinner initialize and fill data and so on.

for each spinner I create them like this and it is iterative:

public ArrayList<MaterialSpinner> spinnerlist = new ArrayList<>();

public void createView(){
 final MaterialSpinner spinner = new MaterialSpinner(context);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){//...after select item next spinner creates with calling createView() iteratively}
        loadSpinnerData(); // set adapter and more
        spinnerlist.add(spinner);
}   

every things go right when select is by user, but when I use setSelection(positionOfItem) Dynamically, unfortunately

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()

do not calls. I do not know why this happens.

   for (int i = 0; i < some_value; i++) {

            int positionOfItem = get_proper_position;
            spinnerList.get(i).setSelection(positionOfItem); //this not trigger onItemSelect!
        }

the problem is here. spinner size is 1 in first time, but after setselection , listener do not calls and second spinner do not creates.

I also thought this is because of time consuming action so try to use a run-able and post some delay but it not worked.

like image 285
Mahdi Avatar asked Oct 29 '22 18:10

Mahdi


1 Answers

I finally find a creepy solution. it seems the problem is with android system that need some time to create item and views. when I call onClickListener of first spinner it should create second one and fill data and it is time consuming action. so I had to put delay for each Item with variable intervals:

for (int i = 0; i < some_value; i++) {
            selectItemOfSpinner(i);
        }


private void selectItemOfSpinner(final int i) {

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            MaterialSpinner spinner = spinnerList.get(i);
            int positionOfItem = get_proper_position;
            spinner.setSelection(positionOfItem, true);
        }
    }, 50*i);

}

this solved my problem and all spinners creates and fills properly. but in some slow device the delay time should increase and this is why i said creepy way. I working on this and I will update the solution if I find a better way.

like image 164
Mahdi Avatar answered Nov 15 '22 06:11

Mahdi