'android - how to set and get value from spinner
I am trying to set and get value to a spinner for item dynamically ?
any ideas ?
I just need help with the Spinner behavior right now, the rest should be quite easy.
Solution 1:[1]
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, android.R.id.text1);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinnerAdapter.add("value");
spinnerAdapter.notifyDataSetChanged();
spinner.setSelection(0);
String text = spinner.getSelectedItem().toString();
Solution 2:[2]
XML file:
<Spinner android:id="@+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Java file:
public class SpinnerExample extends Activity {
private String[] arraySpinner;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.arraySpinner = new String[] {
"1", "2", "3", "4", "5"
};
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arraySpinner);
s.setAdapter(adapter);
}
// To get value from spenner spinner.setOnItemSelectedListener(newAdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView parent, View view, int pos, long id) { Object item = parent.getItemAtPosition(pos); } public void onNothingSelected(AdapterView parent) { } }); }
Solution 3:[3]
Try this this will help you.
Spinner mySpinner= (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> myAdapter= new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item);
mySpinner.setAdapter(myAdapter);
If you want to add the elements dynamically, you can by doing this:
myAdapter.add("newelement");
myAdapter.notifyDataSetChanged();
Solution 4:[4]
Spinner spinn = findViewById(R.id.socialmedia_spinner_adsocmeda);
ArrayList<String> fam = new ArrayList<>();
fam.add("INSTAGRAM");
fam.add("FACEBOOK");
fam.add("GOODWALL");
fam.add("TWITTER");
fam.add("YOUTUBE");
fam.add("LINKEDIN");
fam.add("SNAPCHAT");
ArrayAdapter<String> myAdapter= new ArrayAdapter<String> (ProfileActivity.this,
android.R.layout.simple_list_item_1, fam.toArray(new String[0]));
spinn.setAdapter(myAdapter);
That's a way we can add data to spinner.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | Mridul Shrivastava |
Solution 3 | Murali krishna |
Solution 4 | Gokul Rajendran |