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 數據的方法,根據具體需求選擇適合的方法。