1

I have a spinner dropdown in android and it is populated with list of names as text and ID as value. Now the issue is I have a textbox where user inputs string and on button click item with the name like textbox string should get automatically selected. I searched on google , but couldn't find anything useful. I used

 drpMaterial.setSelection(p);

but it works on index, I was looking for something which will work on text not the value in spinnner dropdown.

My code for populating spinner dropdown:

 Itm=new CItem( "-1", "Select Material" );
                lstItm.add(Itm);
                for(int i=0; i < lengthJsonArr; i++) {

                    jsonmain = j.getJSONObject(i);

                    Itm=new CItem(jsonmain.getString("ID"),jsonmain.getString("Text"));
                    lstItm.add(Itm);


                }
 if(lstItm.size()>0) {
             ArrayAdapter<CItem> adapterProj = new ArrayAdapter<CItem>(myactivity, android.R.layout.simple_spinner_item, lstItm);

             drpProj.setAdapter(adapterProj);
         }
killer
  • 592
  • 1
  • 9
  • 31

2 Answers2

3

You can achieve this by adding this library

Add this to your build.gradle file

dependencies {
...
compile 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1'
}

You can now add in your layout.xml file these lines:

<com.toptoche.searchablespinnerlibrary.SearchableSpinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Add this in your activity and you are good to go!

searchableSpinner.setTitle("Select Item");
searchableSpinner.setPositiveButton("OK");

Check out the link below for more information

https://github.com/miteshpithadiya/SearchableSpinner

Lukas
  • 812
  • 1
  • 14
  • 43
2

If you need to select by value from resource, try to use this code.

 String compareValue= "some value";
 ArrayAdapter<CharSequence> adapter= ArrayAdapter.createFromResource(this, R.array.select_state, android.R.layout.simple_spinner_item);

 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

 MySpinner.setAdapter(adapter);

 if (!compareValue.equals(null)) 
 {
     int spinnerPostion = adapter.getPosition(compareValue);
     MySpinner.setSelection(spinnerPostion);
     spinnerPostion = 0;
 }

for a custom adapter, for example CursorAdapter, you will have to write (override) the code for getPosition()

source: How to set selected item of Spinner by value, not by position?

Community
  • 1
  • 1
anil
  • 2,083
  • 21
  • 37
  • It will only work when item is supplied to getpostion method() with both value and text but I want to search dropdown only by text without considering its value part.@Anil actually I am populating dropdown by arraylist with both text and value parts. – killer May 16 '15 at 11:25