Reputation: 87
How do I get the selected text from a custom spinner?
I have spinner contains name Raju and Rani; if I select "Raju," then "Raju" has to print and if I select "Rani," then "Rani" has to print.
spinnerName = (Spinner)m_view.findViewById(R.id.spinner_name);
ArrayAdapter<String> adapterName = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if (position == getCount()) {
((TextView)v.findViewById(android.R.id.text1)).setText("");
((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount()));
String spinnertext = spinnerCity.getSelectedItem().toString();
System.out.println("spinner" +spinnertext);
}
return v;
}
@Override
public int getCount() {
return super.getCount()-1; // you dont display last item. It is used as hint.
}
};
adapterCity.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapterCity.add("Raju");
adapterCity.add("Rani");
adapterCity.add("name"); //This is the text that will be displayed as hint.
spinnerName.setAdapter(adapterName);
spinnerName.setSelection(adapterName.getCount());
Upvotes: 1
Views: 1393
Reputation: 2188
i think you already populate your spinner . now write this code for get selected text from spinner
spinnerName.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String text = spinnerName.getSelectedItem().toString();
}
}
text contain selected text .. now you can use it as your logic. hope it works ...
Upvotes: 1
Reputation: 12368
Make use on setOnItemSelectedListener. It will return you the selected item of the spinner
Example
spinner.setOnItemSelectedListener(this);
...
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(), "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
}
Upvotes: 0