Spinners in List View
I'm working on an app to identify trees. Therefore, I let the user answer questions about given chara开发者_JAVA百科cteristics, by choosing the appropriate characteristic out of a spinner. Because a tree has many characteristics, I have a whole list of spinners. So far, so good. Unfortunately, the spinners resets, as soon as the user scrolls them off the screen. It is essential, that I can avoid this!
So: How can I avoid this?
I greatly appreciate your help!
public class SearchAdapter extends ArrayAdapter<SearchItem>{
SearchAdapter() {
super(SearchWizard.this, R.layout.question);
}
public View getView(int position, View convertView, ViewGroup parent) {
View ret = convertView;
if ( ret == null ) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ret = inflater.inflate(R.layout.question, null);
}
SearchItem item = getItem(position);
String question = item.getQuestion();
TextView question_text = (TextView) ret.findViewById(R.id.question_search);
assert( question_text != null );
question_text.setText(question);
Spinner question_spinner = (Spinner ) ret.findViewById(R.id.question_spinner);
assert( question_spinner != null );
question_spinner.setPrompt(question);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchWizard.this,android.R.layout.simple_spinner_item, item.getOptions());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
question_spinner.setAdapter(adapter);
question_spinner.setOnItemSelectedListener( new MyOnItemSelectedListener(position) );
question_spinner.setSelection(2);
return ret;
}
}
enter code herepublic class MyOnItemSelectedListener implements OnItemSelectedListener {
public int position;
public MyOnItemSelectedListener(int p) {
position = p;
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
LSsearchCriteria.set(position,Herbalist.encodeoptions(parent.getItemAtPosition(pos).toString()));
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public int position;
public MyOnItemSelectedListener(int p) {
position = p;
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
LSsearchCriteria.set(position,Herbalist.encodeoptions(parent.getItemAtPosition(pos).toString()));
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
You'll need to keep track of the state of the spinners in a separate data structure and when that row is bound again, initialize the spinner with your saved state.
Use Spinner.setSelection(i, true) instead.
Kudos go to Sagi at http://sagistech.blogspot.com/2010/12/spinnersetselection-doesnt-work.html
精彩评论