用SimpleAdapter作为适配器,不报错但是无法运行
package com.example.administrator.spinnerdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private Spinner spinner;
private SimpleAdapter simpleAdapter;
private List<Map<String, Object>> dataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView.setText("你选择的城市是");
//第一步:添加一个下拉列表项list,这里添加的就是下拉列表的菜单项
dataList = new ArrayList<Map<String, Object>>();
//getData();
textView = findViewById(R.id.text);
spinner = findViewById(R.id.spinner);
//第二步:为下拉列表定义一个适配器,这里就会用到list
simpleAdapter = new SimpleAdapter(this, getData(), R.layout.item, new String[]{"pic", "text1"}, new int[]{R.id.pic, R.id.text1});
//第三步:为适配器设置下拉样式
simpleAdapter.setDropDownViewResource(R.layout.item);
//第四步:将适配器添加到下拉列表中
spinner.setAdapter(simpleAdapter);
//第五步:为下拉列表设置各种响应事件,事件响应菜单被选中
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//将你选的值带入到textView
String cityName = (String) simpleAdapter.getItem(position);
textView.setText("你选择的是" + cityName);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
textView.setText("NONE");
}
});
}
private List<Map<String, Object>> getData() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("pic", R.mipmap.ic_launcher);
map.put("text1", "北京");
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("pic", R.mipmap.ic_launcher);
map1.put("text1", "厦门");
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("pic", R.mipmap.ic_launcher);
map2.put("text1", "天津");
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("pic", R.mipmap.ic_launcher);
map3.put("text1", "上海");
dataList.add(map);
dataList.add(map1);
dataList.add(map2);
dataList.add(map3);
return dataList;
}
}