Spinner 数据动态加载方法有以下几种方式:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yourDataList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
List<Map<String, String>> data = new ArrayList<>();
for (String item : yourDataList) {
Map<String, String> map = new HashMap<>();
map.put("text", item);
data.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_spinner_item, new String[] {"text"}, new int[] {android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
BaseAdapter adapter = new BaseAdapter() {
@Override
public int getCount() {
return yourDataList.size();
}
@Override
public Object getItem(int position) {
return yourDataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
}
TextView textView = convertView.findViewById(android.R.id.text1);
textView.setText(yourDataList.get(position));
return convertView;
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
以上是几种常见的动态加载 Spinner 数据的方法,根据具体需求选择适合的方法。