I have asked this before, but I was too general.
I have an activity with two radio buttons and only two arrays: String[] tickets;
which has 3 items and String[] subscriptions;
which has 5 items. By the way, the radio buttons are inside a radioGroup.
The first radioButton is for String[] tickets;
and the second radioButton is for String[] subscriptions;
When I check the first radioButton, I want the spinner to be populated by the items in String[] tickets
and when I check the second radioButton I want the spinner to be populated by the items in String[] subscriptions;
But how do you do that? I tried using a temporary array which is empty and used it as the array source for the spinner. I would then place one of these arrays inside the empty one. But it did not work.
EDIT:
MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String[] tickets = {"Ticket #1", "Ticket #2", "Ticket #3"};
String[] subscriptions = {"Sub #1", "Sub #2", "Sub #3", "Sub #4", "Sub #5"};
String[] tempArray;
Spinner spinner1;
RadioGroup radioGroup;
RadioButton radioButtonOption;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
int selectedRadioButton = radioGroup.getCheckedRadioButtonId();
radioButtonOption = (RadioButton)findViewById(selectedRadioButton);
spinner1 = (Spinner)findViewById(R.id.spinner1);
radioButtonOption.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (radioButtonOption.getText().equals("Journeys/Tickets")) {
tempArray = tickets;
} else if (radioButtonOption.getText().equals("Subscription")) {
tempArray = subscriptions;
}
}
});
spinner1.setOnItemSelectedListener(this);
ArrayAdapter a1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, tempArray);
a1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(a1);
spinner1.setOnItemSelectedListener(this);
Try this
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
spinner1 = (Spinner)findViewById(R.id.spinner1);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId)
{
case R.id.button_1:
a1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item ,tickets);
spinner1.setAdapter(a1);
break;
case R.id.button_2:
a1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item,subscriptions);
spinner1.setAdapter(a1);
break;
}
a1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
});
spinner1.setOnItemSelectedListener(this);
Note you need to declare ArrayAdapter a1;