简单的spinner举例,一言不合上代码:
public class SpinnerActivity extends BaseActivity {
private TextView textView,textView1;
private Spinner spinner_1;
private ArrayAdapter<String> adapter_1;
private List<String> lists_1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_layout);
spinner_1 = (Spinner) findViewById(R.id.spinner_1);
textView = (TextView) findViewById(R.id.textView);
//1.设置数据源
lists_1 = new ArrayList<String>();
lists_1.add("北京");
lists_1.add("上海");
lists_1.add("广州");
lists_1.add("深圳");
//2.设置适配器
adapter_1 = new ArrayAdapter<String>(SpinnerActivity.this, android.R.layout.simple_spinner_item, lists_1);
//3.设置下拉样式
adapter_1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//4.加载适配器
spinner_1.setAdapter(adapter_1);
//5.设置监听
spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String cityName = adapter_1.getItem(position);
textView.setText("您选择了: " + cityName);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
}
第2步加载适配器和第3步设置下拉样式都是采用android自带的样式哦
自定义spinner控件:
//1.设置数据源
getData();
//2.配置适配器
adapter_2 = new SimpleAdapter(SpinnerActivity.this,lists_2,R.layout.spinner_item,new String[]{"image","text"},new int[]{R.id.image,R.id.textView});
//3.设置下拉样式
adapter_2.setDropDownViewResource(R.layout.spinner_item);
//4.加载适配器
spinner_2.setAdapter(adapter_2);
//5.设置监听
spinner_2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String cityName = lists_2.get(position).get("text").toString();
textView1.setText("您选择了: "+cityName);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private List<Map<String, Object>> getData() {
lists_2 = new ArrayList<Map<String, Object>>();
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("image", R.mipmap.ic_launcher);
map1.put("text", "北京");
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("image", R.mipmap.ic_launcher);
map2.put("text", "上海");
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("image", R.mipmap.ic_launcher);
map3.put("text", "广州");
Map<String, Object> map4 = new HashMap<String, Object>();
map4.put("image", R.mipmap.ic_launcher);
map4.put("text", "深圳");
lists_2.add(map1);
lists_2.add(map2);
lists_2.add(map3);
lists_2.add(map4);
return lists_2;
}
依然是SimpleAdapter的使用,不过这一次子项布局采用了我们自创的布局哦(左边ImageView右边TextView)
注意,监听事件是setOnItemSelectedListener!!还有不要忘了setDropDownViewResource来设置下拉菜单的样式哦