I want to build android app with spinner , I would like to appear in spinner some text , and when selected, it appears in TextView other text than the value of which is a selected.
for example , i want to appear in spinner website name (like= stackoverflow) and when select appear in TextView the website URL (like=https://stackoverflow.com/)
can anyone help me?
thanks in advance
First, you create yourself an Object:
public class LanguageObject {
private String title;
private String url;
public LanguageObject(String title, String url) {
this.title = title;
this.url = url;
}
public String getTitle() {
return title;
}
public Integer getUrl() {
return url;
}
}
Then, in your Activity/Fragment, you create an ArrayList with the objects you need:
ArrayList<SpinnerObject> spinnerObjectList = new ArrayList<SpinnerObject>();
spinnerObjectList.add(new SpinnerObject("Google", "www.google.com"));
spinnerObjectList.add(new SpinnerObject("StackOverflow", "www.stackoverflow.com"));
In addition to that, create a custom adapter that will handle your data:
public class SpinnerAdapter extends ArrayAdapter<SpinnerObject> {
public SpinnerAdapter (Context context, int textViewResourceId, ArrayList<SpinnerObject> spinnerObjects) {
super(context, textViewResourceId, spinnerObjects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
SpinnerObject spinnerObject = getItem(position);
if(view == null) {
LayoutInflater layoutInflater;
layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(android.R.layout.select_dialog_item, null);
if (view != null) {
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setText(spinnerObject.getTitle());
}
}
return view;
}
Now you can use this adapter on your Spinner, and get the url when one of the items was clicked.
You can add text to spinner like this:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> texts = new ArrayList<String>();
texts.add("Google");
texts.add("Facebook");
List<String> urls = new ArrayList<String>();
urls.add("www.google.com");
urls.add("www.facebook.com");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, texts);
spinner.setAdapter(adapter);
then you need to listen for item selected on spinner
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String url = urls.get(i);
// do with url whatever you need
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// do nothing
}
});
For adding text in spinner you can use following code in onCreate()
Spinner locale;
ArrayList<String> lList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locale =(Spinner)findViewById(R.id.Cmblocale);
// bind data to Spinner(ComboBox)
lList =new ArrayList<String>();
lList.add("English");
lList.add("Canada");
lList.add("Chinese");
lList.add("French");
lList.add("Germany");
lList.add("Japan");
ArrayAdapter<String> cAdapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,lList);
locale.setAdapter(cAdapter);
}
For Retrieving value use following code inside your setOnItemSelectedListener on spinner
if(locale.getSelectedItem().equals("English"))
{
txtText.setText(English);
}else if(locale.getSelectedItem().equals("Chinese"))
{
txtText.setText(Chinese);
}else if(locale.getSelectedItem().equals("Canada"))
{
txtText.setText(Canada);
}else if(locale.getSelectedItem().equals("French"))
{
txtText.setText(French);
}else if(locale.getSelectedItem().equals("Germany"))
{
txtText.setText(Germany);
}else if(locale.getSelectedItem().equals("Japan"))
{
txtText.setText(Japan);
}
Spinner spinner = (Spinner) findViewById(R.id.spinner); //create a spinner view in XML
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.your_array, android.R.layout.simple_spinner_item); // create adapter which has second parameter as the array which contains the values you want to show as entries of spinner
spinner.setAdapter(adapter); // set the adapter to your spinner and your spinner will show the values from array that you set in second parameter of adapter
To listen to the click on the options of the spinner
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
Now to show the appropriate link of the website for selected option from spinner you can have a map which has keys as same as the spinner values and values as websites as you want....
HashMap<String, String> nameWebsiteMap = new HashMap<String, String>();
nameWebsite.put("stack overflow","http://stackoverflow.com/"); // for example
So in onItemSelected you can simply do this
selectedSiteName = nameWebsite.get(parent.getItemAtPosition(pos).toString());
textView.setText(selectedSiteName);
Related
I want to get information using putExtra() on another page and I can do it, but my only problem is always the default value the first value sample_array but i want to by default classDayIntent value is displayed in spinner
tip: The putExtra() received in Spinner is there
First Activity:
Intent intent = new Intent();
intent.putExtra("className" , className);
intent.putExtra("uniName" , uniName);
intent.putExtra("classDay" , classDay);
intent.setClass(context , AddNewClass.class);
context.startActivity(intent);
Second Activity:
Spinner spinner = (Spinner)findViewById(R.id.spinnerDay);
String className = getIntent().getStringExtra("className");
String uniName = getIntent().getStringExtra("uniName");
String classDayInent = getIntent().getStringExtra("classDay"); // How To Display classDayInent In Spinner....
className_EditeText.setText(className);
uniName_EditeText.setText(uniName);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this , R.array.sample_array , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String classDay = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Strings:
<resources>
<string name="app_name">ClassManager</string>
<string-array name="sample_array">
<item>شنبه</item>
<item>یکشنبه</item>
<item>دوشنبه</item>
<item>سه شنبه</item>
<item>چهارشنبه</item>
<item>پنجشنبه</item>
<item>جمعه</item>
</string-array>
you can use add function of adapter.
since CharSequence is an interface, and the String class implements CharSequence so you can directly add string to adapter
adapter.add(classDayInent);
spinner.setAdapter(adapter);
Another issue is , createFromResources creates a immutable list mean it cannot add more items.
Solution : create your own adapter with mutable list
List<String> list = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sample_array)));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this , android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
list.add(0,classDayIntent);// to add received element at first position to display
spinner.setAdapter(adapter);
You can get your xml arraylist and then add to that:
List<String> ar = new LinkedList<String>(Arrays.asList(getResources().getStringArray(R.array.sample_array)));
ar.add("test");
i found correct answer :
String classDayInent = getIntent().getStringExtra("classDay");
List<String> list = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.sample_array)));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this , android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
//find classDayIntent from List For get Position To Display
for (int i = 0; i < list.size(); i++)
{
if (classDayIntent.equals(list.get(i)))
{
spinner.setSelection(i);
}
}
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
classDay = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I don't know how to set the selected country isd code in
spinner.Below I have posted the code what I have been tried so far:
MainActivity.java:
public class MainActivity extends Activity implements OnItemSelectedListener {
ArrayList<String> arrCode;
ArrayList<String> arrCountry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
arrCode = new ArrayList<>();
arrCountry = new ArrayList<>();
arrCountry.add("US");
arrCountry.add("KZ");
arrCountry.add("EG");
arrCountry.add("ZA");
arrCountry.add("GR");
arrCode.add("1");
arrCode.add("7");
arrCode.add("20");
arrCode.add("27");
arrCode.add("30");
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrCountry);
adapter_state.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_mobile_code.setAdapter(adapter_state);
sp_mobile_code.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
int spinnerValue1 = sp_mobile_code.getSelectedItemPosition();
String data = arrCode.get(spinnerValue1);
Log.e("data", "" + data);
sp_mobile_code.setPrompt(data);
/* sp_mobile_code.setSelection(position);*/
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
My issue is : I can't set the isd code in same spinner.If I have to
set isd code in textview means it will be easy.But I have to set it
in the spinner
Edit: spinner list showing correctly the country list.on clicking the country list, I have to show the isd code
Use Custom ArrayAdapter.
private static class CustomSpinnerAdapter extends ArrayAdapter<String>
{
List<String> arrCodes;
public CustomSpinnerAdapter(Context context, int resource, List<String> items, List<String> arrCodes)
{
super(context, resource, items);
this.arrCodes = new ArrayList<>();
this.arrCodes = arrCodes;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
TextView view = (TextView) super.getView(position, convertView, parent);
view.setText(arrCodes.get(position));
return view;
}
}
Check the position in the getView() and set text of your desire. Use this adapter for the Spinner
Here is my code below, which is getting item from spinner on click
public class SpinnerActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner spinner1,spinner2,spinner3;
private static final String[] sports = {
"Hockey","Cricket","Football","Basketball","Badminton","Tennis"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
spinner1 = (Spinner)findViewById(R.id.drop_down);
spinner2 = (Spinner)findViewById(R.id.drop_down2);
spinner3 = (Spinner)findViewById(R.id.drop_down3);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,sports);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner2.setAdapter(adapter);
spinner3.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
How do I preserve the selected spinners' item even after exiting the application?
You can use SharedPreference to store the selected value position/id/string.
Simply add this line when you get String item
Editor edit = context.getSharedPreferences("Name_of_sf",Context.MODE_PRIVATE).edit();
edit.putString("selected_item", item);
edit.commit();
And can simply retrieve the value as
context.getSharedPreferences("Name_of_sf",Context.MODE_PRIVATE).getString("selected_item", "");
For more info #AnirudhSohil you could see the official documentation, it has a very detail examples, I hope that it helps you.
http://developer.android.com/training/basics/data-storage/shared-preferences.html
I have a spinner which displays both options, but when I accept the female option, it still takes the answer as a male, any suggestions?
List<String> SpinnerArray = new ArrayList<String>();
SpinnerArray.add("Male");
SpinnerArray.add("Female");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SpinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Items = (Spinner) findViewById(R.id.genderSpinner);
Items.setAdapter(adapter);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
String selected = Items.getSelectedItem().toString();
if (selected.equals("Male")) {
inputGen = "Male";
}
if (selected.equals("Female")){
inputGen = "Female";
}
Following the official guide:
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
...
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
You can try a switch of position and then try your same conditions.
My activity contains a button and a ListView. The ListView contains a Spinner and an EditText view. I use the button each time I want to insert a new row entry in my Activity's ListView.
I have followed the instructions of previous stackoverflow threads like this one here: Android Listview with spinner and a checkbox on how to populate ListViews with focusable objects like Spinners.
My problem is that each time I dynamically add a new ListView entry in the ListView, the Spinner value of the previous ListView entry is lost (actuall the Spinner returns to its default setting). Say for simplicity that my Spinners are populated with the following data:
String spinner_data[] = {"apple", "banana", "pear", "watermelon", "strawberry"};
For example, if I select my first ListView's Spinner value to be "pear" and then I add a new ListView entry with my Button, the "pear" entry disappears from the 1st ListView Spinner and the default value "apple" appears).
Any help is appreciated!
This is my activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView) findViewById(R.id.lv);
da = new DataAdapter(this, new ArrayList<RawData>());
lv.setAdapter(da);
btn_new = (Button)findViewById(R.id.btn_new);
btn_new.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
da.add(new RawData(this));
da.notifyDataSetChanged();
}
});
}
The RawData class is this one:
public class RawData {
private int selected_position;
private ArrayAdapter<CharSequence> adapter;
public RawData(Context context)
{
adapter = ArrayAdapter.createFromResource(context, R.array.data, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
public ArrayAdapter<CharSequence> getAdapter()
{
return adapter;
}
/**
* get adapter's item text from selected position
* #return
*/
public String getText()
{
return (String) adapter.getItem(selected_position);
}
public int getSelected()
{
return selected_position;
}
public void setSelected(int selected)
{
this.selected_position = selected;
}
}
The DataArrayAdapter is the following:
public class DataArrayAdapter extends ArrayAdapter<RawData> {
private Activity myContext;
//private final List<RawData> list;
public DataArrayAdapter(Activity context, List<RawData> list)
{
super(context, R.layout.row_view, list);
myContext = context;
}
static class ViewHolder
{
protected RawData data;
protected Spinner spn;
protected EditText edt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = null;
if ( convertView == null )
{
LayoutInflater inflator = myContext.getLayoutInflater();
view = inflator.inflate(R.layout.row_view, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.edt = (EditText)view.findViewById(R.id.edt);
viewHolder.data = new RawData(myContext);
viewHolder.spn = (Spinner)view.findViewById(R.id.spn);
viewHolder.spn.setAdapter(viewHolder.data.getAdapter());
viewHolder.spn.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2_position, long arg3) {
// TODO Auto-generated method stub
viewHolder.data.setSelected(arg2_position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// Update the TextView to reflect what's in the Spinner
view.setTag(viewHolder);
}
else
{
view = convertView;
}
// This is what gets called every time the ListView refreshes
ViewHolder holder = (ViewHolder) view.getTag();
holder.spn.setSelection(getItem(position).getSelected());
return view;
}
}
You're not handling the situation when getView gets a non-null convertView. In your example, after you add an item, ListView refreshes itself, and position that should display 'pear' gets an existing convertView (the one that was used previously to display 'apple') and you just pass it along to ListView without setting the data for current position. You cannot rely on ListView items to store any data, you should always set correct contents for position in getView method of your adapter.
Just to be clear, I see that your code sets the selected position in the end of getView but the issue is that whatever is tagged to your convertView when it is passed to getView by recycler mechanism in ListView is random and can be associated with any position it used to display before.
To make your application work you'll have to create array of selectedItem values for all your spinners, and attach it as a member to your adapter. You'll have to update the corresponding value on each OnItemSelected event and you'll add a new value for each "add" button click. And when you prepare your view in getView you'll just set the selected spinners index to corresponding value in your array.