I have two spinners, such that my second spinner changes options that it can offer according to the item selected in the first spinner. Easy?
Example: If I select 'a' in main spinner, the sub spinner should show 'a1' as option. If I select 'b' in main spinner, the sub spinner should show 'b1','b2' as options. If I select 'c' in main spinner, the sub spinner should show 'c1','c2','c3' as options.
I use a library called SearchableSpinner but that does not matter as it works just like the Android spinner.
public class PostComplaint extends AppCompatActivity {
String[] problems_main = {"a","b","c"};
String[][] problems_sub = {{"a1"},{"b1","b2"},{"c1","c2","c3"}};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_complaint);
spinner_main = (SearchableSpinner)findViewById(R.id.spinner_main);
spinner_sub = (SearchableSpinner) findViewById(R.id.spinner_sub);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, problems_main);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_main.setAdapter(spinnerAdapter);
spinnerAdapter.notifyDataSetChanged();
spinner_main.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
setSubSpinner(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(PostComplaint.this, "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
}
void setSubSpinner(int i){
String[] myArray = problems_sub[i]; //Note: problems_sub is a two dimensional array
ArrayAdapter<String> spinnerAdapter_sub = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, myArray);
spinnerAdapter_sub.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_sub.setAdapter(spinnerAdapter_sub);
spinnerAdapter_sub.notifyDataSetChanged();
}
Problem: Whichever item I click on the main spinner for the first time, according to that the sub spinner is selected. Then if I change the main spinner, the sub spinner is not changing.
The question is open for suggestions. Comment if it is not understandable.