Search code examples
androidandroid-spinner

Change Android Spinner 1st item background color


I want to change a spinner's 1st dropdown menu background color. Is it possible? For example, I have 3 items menu for gender selection. 1) Select your gender 2) Male 3) Female. I want to show these 3 items in the spinner dropdown. I want to change the background of 1st item as light blue and the other 2 items should be white. Is it possible


Solution

  • How about use spinner Adapter?

    for Example,

    ArrayList<String> testarray = new ArrayList<String>();
        testarray.add("item0");
        testarray.add("item1");
        testarray.add("item2");
        testarray.add("item3");
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, testarray) {
    
           @Override      
           public boolean isEnabled(int position) {
               return position != 1;                             
           }
    
           @Override                
           public boolean areAllItemsEnabled() {
               return false;
           }
    
           @Override
           public View getDropDownView(int position, View convertView, ViewGroup parent){
               View v = convertView;
               if (v == null) {
                   Context mContext = this.getContext();
                   LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                   v = vi.inflate(R.layout.row, null);
               }
    
               TextView tv = (TextView) v.findViewById(R.id.spinnerTarget);
               tv.setText(testarray.get(position));
    
               switch (position) {
                   case 0:
                       tv.setTextColor(Color.RED);  
                       break; 
                   case 1:
                       tv.setTextColor(Color.BLUE);
                       break;
                   default:
                       tv.setTextColor(Color.BLACK);
                       break;
               }
               return v;  
           }              
        };
    
        pSpinner.setAdapter(spinnerAdapter); 
    

    and this is simple_spinner_dropdown_item.xml for row.

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spinnerTarget"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="14pt" />
    

    exmaple code change textColor. So you can try to change Background color