I have a spinner in a dialog and I am trying to get the value from the selected item in spinner and pass it to a String variable. The method that I have found was spinner.setOnItemSelectedListener().
However, this method requires another method to be set up outside the dialog. Code attached below.
This is the code of the dialog
private void recordDialog() {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
View subView = inflater.inflate(R.layout.record, null);
//get current date
Calendar calendar = Calendar.getInstance();
String pattern = "dd-MMM-yy";
DateFormat dateFormat = new SimpleDateFormat(pattern);
final String currentDate = dateFormat.format(calendar.getTime());
//get category
final Spinner spinner = subView.findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
...
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
And the part outside the dialog
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedCategory = parent.getItemAtPosition(position).toString();
}
Is there anyway to complete everything within the dialog?
Well you could just implement the onItemSelectedListener
inside your recordDialog
function:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// Do your stuff here
}
public void onNothingSelected(AdapterView<?> parent) {
// Do your stuff here
}
});
}