I need my spinners to have two different textcolors (green = ok, red = not ok), depending on the "mastervalue".
For example:
If mastervalue = 1:
Spinner 1
Spinner 2
If mastervalue = 2:
Spinner 1
Spinner 2
So the colors have to change dynamically, every time I change the mastervalue. To check which values are green/red, I have a couple of many-to-many relationship tables in my db. I just have to find a way to set the text color for each value before/after populating a spinner.
Would be great to get some help here!
For your issue you simply need to create a simple custom SpinnerAdapter and manipulate it as you need:
1.First of all let's create a custom_spinner row (layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text_main_seen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
public class MyAdapter extends ArrayAdapter<String> {
String[] spinnerValues;
public MyAdapter(Context ctx, String[] objects) {
super(ctx, R.layout.custom_spinner, objects);
spinnerValues = objects;
}
@Override public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
@Override public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.custom_spinner, parent, false);
TextView main_text = (TextView) mySpinner .findViewById(R.id.text_main_seen);
//here you make the algorithm you want for coloration///////////////////////////
if(spinnerValues[position].equals("blue")){
mySpinner.setBackgroundColor(Color.BLUE);
}else if(spinnerValues[position].equals("green")){
mySpinner.setBackgroundColor(Color.GREEN);
}else if(spinnerValues[position].equals("red")){
mySpinner.setBackgroundColor(Color.RED);
}else if(spinnerValues[position].equals("yellow")){
mySpinner.setBackgroundColor(Color.YELLOW);
}
//end coloration algorithm//////////////////////////////////////////
main_text.setText(spinnerValues[position]);
return mySpinner;
}
}
And finally in your activity you refere to this Adapter in your spinner:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//values to put in the spinner
String[] values = { "blue", "red", "green", "yellow" };
//my spinner
Spinner mySpinner = (Spinner) findViewById(R.id.spinner_show);
//set MyAdaper
mySpinner.setAdapter(new MyAdapter(this, values));
}
}
At the end this is a simple test if it's needed ;)
Good luck , just let me know if anything goes wrong ;)