Android - Text dropdown/selection of Spinner does not show

前端 未结 3 2111
野的像风
野的像风 2021-01-05 23:49

I\'m using this sample code to populate the Spinner. Data is read from database. The selection displays correctly - in this case, it shows \"Green\" and \"Red\".

<         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 00:38

    Ok, what's happening is that when you're calling setDropDownViewResource you're replacing the layout you previously specified in the constructor. In your case R.layout.profile_color. SimpleCursorAdapter extends ResourceCursorAdapter and in the constructor sets the two layouts equal to each other.

    public ResourceCursorAdapter(Context context, int layout, 
        Cursor c, boolean autoRequery) {
    
        super(context, c, autoRequery);
        mLayout = mDropDownLayout = layout;
        mInflater = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    

    The issue arises when you call setDropDownViewResource and change the drop down layout. The SimpleCursorAdapter will continue to use the same resource id bindings that you specified in the constructor.

    What you should do is only specify the layout in the SimpleCursorAdapter's constructor. I suggest changing your code to as follows:

    String[] from = new String[] { ProfileDbAdapter.COL_PROFILE_TITLE };
    int[] to = new int[] { android.R.id.text1 }; // from simple_spinner_dropdown_item
    
    SimpleCursorAdapter profilesAdapter = new SimpleCursorAdapter(this,
            android.R.layout.simple_spinner_dropdown_item, profilesCursor, from, to);
    
    spinnerColor.setAdapter(profilesAdapter);
    

    To get the results you want.

    Basically don't use the setDropDownViewResource method. Or, if you do, and you change the resource id bindings, you'll have to call SimpleCursorAdapter#changeCursorAndColumns; however, that is probably overkill for the simple result you're trying to achieve.

提交回复
热议问题