这个东东大家在开发中可能不太能用到,所以总是容易被忽略,由于工作原因,我最近琢磨了一下onNothingSelected方法的调用时机问题,其实很简单,只要我们稍微看一下源码就明白了:
/** * Callback method to be invoked when the selection disappears from this * view. The selection can disappear for instance when touch is activated * or when the adapter becomes empty. * * @param parent The AdapterView that now contains no selected item. */ void onNothingSelected(AdapterView<?> parent);
源码里边说的很明白了,当我们的adapter为空的时候就会调用到这个方法,那么我做了一个小Demo,来测试一下这个效果,核心代码如下:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); provinces = (Spinner) this.findViewById(R.id.provinces); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, data); provinces.setAdapter(adapter); provinces.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.d("qianfeng", "您选择了" + data.get(position)); } @Override public void onNothingSelected(AdapterView<?> parent) { Log.d("qianfeng", "NothingSelected"); } }); } /** * 点击button时,将集合中的数据全部移除,同时调用adapter的notifyDataSetChanged方法 * @param view */ public void btnClick(View view){ data.removeAll(data); adapter.notifyDataSetChanged(); } private void initData() { data = new ArrayList<String>(); data.add("山东"); data.add("广西"); data.add("陕西"); data.add("广东"); }
我们来看一下运行效果: