public class MainActivity extends AppCompatActivity {
ArrayList<String> list = new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayList<String> data1 = new ArrayList<>();
ArrayList<String> data2 = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0 ; i< 10 ;i++){
data1.add(String.valueOf(i));
}
for (int i = 20; i < 30; i++){
data2.add(String.valueOf(i));
}
Spinner spinner = (Spinner) findViewById(R.id.demo);
adapter = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,list);
spinner.setAdapter(adapter);
}
private void change(boolean which){
if (which){
list.clear();
list.addAll(data1);
}else{
list.clear();
list.addAll(data2);
}
adapter.notifyDataSetChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_no) {
change(true);
return true;
}else if (id == R.id.action_ok){
change(false);
return true;
}
return super.onOptionsItemSelected(item);
}
}
当我在下拉菜单中交换数据时,会出现错误:
08-25 11:51:59.630 29087-9866/me.aber.app.arrayapdapterdemo
D/dalvikvm? GC_FOR_ALLOC freed 2055K, 52% free 7378K/15192K, paused 24ms, total 30ms
08-25 11:52:01.923 29087-9866/me.aber.app.arrayapdapterdemo
W/Binder? Caught a RuntimeException from the binder stub implementation.
java.lang.NullPointerException
at android.view.WindowManagerGlobal.dumpGfxInfo(WindowManagerGlobal.java:437)
at android.app.ActivityThread$ApplicationThread.dumpGfxInfo(ActivityThread.java:1021)
at android.app.ApplicationThreadNative.onTransact(ApplicationThreadNative.java:550)
at android.os.Binder.execTransact(Binder.java:404)
at dalvik.system.NativeStart.run(Native Method)
我点击操作时,这个出现的很随机。