温馨提示×

android spinner数据动态加载方法

小樊
99
2024-08-02 16:34:14
栏目: 编程语言

Spinner 数据动态加载方法有以下几种方式:

  1. 使用 ArrayAdapter:
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);
  1. 使用 SimpleAdapter:
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);
  1. 使用 BaseAdapter:
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 数据的方法,根据具体需求选择适合的方法。

0