Wednesday, March 6, 2019

Android开发笔记-ch3.2.3 Spinner


3.2.3 Spinner

Refer to spinner. It is not listed at https://www.google.com/design/spec/components: To define the selection event handler for a spinner, implement the AdapterView.OnItemSelectedListener interface and the corresponding onItemSelected() callback method.
The callback of onItemSelected() has to be armed by calling setOnItemSelectedListener. And note the callback won't be invoked if the position has not been changed, even the user selects again. If want the behavior of keep triggering, refer to this SO to extend the spinner class. However there is limitation: (NDSpinner) findViewById(R.id.spinner_account) will cause java.lang.ClassCastException because findViewById returns instance of android.support.v7.widget.AppCompSpinner which cannot be casted to the subclass of Spinner. A lot of discuss at SO regarding mis-fire of the callback, two main ideas:
Method A: setup the listerner as last will avoid it gets called earlier
spinner.setAdapter(adapter);
spinner.setSelection(0, false); //animate=false, not bring it to life => no event/callback?
spinner.setOnItemSelectedListener(this);
Method B: using Runnable:
 spinner.post(new Runnable() {
     public void run() {
         spinner.setOnItemSelectedListener(listener);
     }
 });
Here is an example code for dynamically add/remove item in spinner:
Spinner toList;
ArrayAdapter<String> dataAdapter;

public void onCreate(Bundle savedInstanceState) {
...
toList = (Spinner) findViewById(R.id.toList);
dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,
new ArrayList<String>());
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
toList.setAdapter(dataAdapter);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(this);
Button remove = (Button) findViewById(R.id.remove);
remove.setOnClickListener(this);
}

public void onClick(View v) {
String myData = fromList.getSelectedItem().toString();
int position = dataAdapter.getPosition(myData);
switch (v.getId()) {
case R.id.add:
if(position >= 0){
Toast.makeText(getBaseContext(), myData+" already in Spinner", Toast.LENGTH_LONG).show();
}
else {
dataAdapter.add(myData);
dataAdapter.notifyDataSetChanged();
toList.setSelection(dataAdapter.getPosition(myData));
}
break;
case R.id.remove:
if(position >= 0){
dataAdapter.remove(myData);
dataAdapter.notifyDataSetChanged();
}
else {
Toast.makeText(getBaseContext(), myData + " not in Spinner", Toast.LENGTH_LONG).show();
}
break;
}
}

0 Comments:

Post a Comment