Spinner displaying first item text while other item is selected

試著忘記壹切 提交于 2019-12-08 02:32:02

问题


I have a Spinner which is filled by a SimpleCursorAdapter within the onResume() method. The selection is also set in onResume: spinner.setSelection(x).

When I go to another activity and then go back to this activity, the Spinner shows the text of the first item, instead of the text of the selected item.

How do I fix this?

EDIT: Here's my code:

@Override
public void onResume(){
    super.onResume();
    fillSpinner();
}

private void fillSpinner() {
    Db = new DbAdapter(this);
    Db.open();
    final Cursor cursor = Db.getCats(true,true);
    startManagingCursor(cursor);

    String[] from = new String[]{DbAdapter.KEY_NAME};
    int[] to = new int[]{android.R.id.text1};

    SimpleCursorAdapter adapter =
            new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, from, to);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(adapter);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            cursor.moveToPosition(pos);
            spinnerval = cursor.getInt(cursor.getColumnIndexOrThrow(DbAdapter._ID));
            Log.d("spinnerval", spinnerval+"");
        }
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    spinner.setSelection(0);
    int now = hour*60*60+minute*60;
    Log.d("fillSpinner","now="+now+" / "+now/60.0/60.0);
    cursor.moveToFirst();
    while(cursor.moveToNext()){
        int s = cursor.getInt(cursor.getColumnIndexOrThrow(DbAdapter.KEY_START));
        int e = cursor.getInt(cursor.getColumnIndexOrThrow(DbAdapter.KEY_END));
        if(e<s){
            if(now>s){
                e+=24*60*60;
            }
            else{ 
                s-=24*60*60;
            }               
        }
        if(s<=now&&e>now){
            spinner.setSelection(cursor.getPosition());
        }
    }


    Db.close();

    spinner.invalidate();

}

EDIT2: Screenshot:


回答1:


Changing spinner.setSelection(cursor.getPosition()) to spinner.setSelection(cursor.getPosition(),true) did the trick.




回答2:


I fought this same problem too. here's what I suggest:

add at the beginning of fillSpinner()

int spinnerDefault = 0;

next add your logic for changing the selection before setting up the spinner. use this to change spinnerDefault variable.

Then right after the line:

spinner.setAdapter(adapter);

add:

spinner.setSelection(spinnerDefault);




回答3:


you have set spinner.setSelection(0);

so it will show by default first item.



来源:https://stackoverflow.com/questions/12159889/spinner-displaying-first-item-text-while-other-item-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!