How to change Spinner item background color in Android, How to set Spinner alternate item color in Android
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#67a79c"
>
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textStyle="italic"
android:fontFamily="sans-serif-medium"
/>
MainActivity.java
package com.cfsuman.me.androidcodesnippets;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get reference of widgets from XML layout
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Initializing a String Array
String[] plants = new String[]{
"Laceflower",
"California sycamore",
"Mountain mahogany",
"Butterfly weed",
"Carrot weed"
};
final List<String> plantsList = new ArrayList<>(Arrays.asList(plants));
// Initializing an ArrayAdapter
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this,R.layout.spinner_item,plantsList){
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position%2 == 1) {
// Set the item text color
tv.setTextColor(Color.parseColor("#FF7C7967"));
// Set the item background color
tv.setBackgroundColor(Color.parseColor("#FFC3C0AA"));
}
else {
// Set the alternate item text color
tv.setTextColor(Color.parseColor("#FF657A86"));
// Set the alternate item background color
tv.setBackgroundColor(Color.parseColor("#FFB5DCE8"));
}
return view;
}
};
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
spinner.setAdapter(spinnerArrayAdapter);
}
}
output