How to use SparseArray as a source for Adapter?

此生再无相见时 提交于 2020-01-14 09:35:08

问题


I have a sparse array of values which I want to populate in a Spinner, and when the item is selected, I want to get the id (which is the key from the sparse array).

What is the preferred way of creating an adapter from a SparseArray?

Is it possible to subclass an existing Adapter like BaseAdapter or ListAdapter So that the items will have a key from the SparseArray as item id?

Not knowing how to achieve the above, I am thinking of creating a simple ArrayAdapter instance and giving it values from the SparseArray as a source and when the item is selected, to look up the key by the value, which I think won't be efficient.


回答1:


Creating a subclass of BaseAdapter should work fine. E.g. take

public abstract class SparseArrayAdapter<E> extends BaseAdapter {

    private SparseArray<E> mData;
    public void setData(SparseArray<E> data) {
        mData = data;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public E getItem(int position) {
        return mData.valueAt(position);
    }

    @Override
    public long getItemId(int position) {
        return mData.keyAt(position);
    }
}

and extend that one to get some actual functionality. For example like

public class SparseStringsAdapter extends SparseArrayAdapter<String> {
    private final LayoutInflater mInflater;
    public SparseStringsAdapter(Context context, SparseArray<String> data) {
        mInflater = LayoutInflater.from(context);
        setData(data);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView result = (TextView) convertView;
        if (result == null) {
            result = (TextView) mInflater.inflate(android.R.layout.simple_list_item_1, null);
        }
        result.setText(getItem(position));
        return result;
    }
}


来源:https://stackoverflow.com/questions/21677866/how-to-use-sparsearray-as-a-source-for-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!