如何使用SparseArray作为适配器的源? [英] How to use SparseArray as a source for Adapter?

查看:84
本文介绍了如何使用SparseArray作为适配器的源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在Spinner中填充的值的稀疏数组,选择该项目后,我想获取id(这是稀疏数组的键).

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).

从SparseArray创建适配器的首选方法是什么?

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

是否可以继承现有适配器(如BaseAdapter或ListAdapter)的子类,以便使这些项具有SparseArray中的项作为项ID?

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?

我不知道如何实现上述目标,我正在考虑创建一个简单的ArrayAdapter实例,并从SparseArray中为其提供值作为源,并在选择该项目时通过该值查找键,我认为这是成功的效率不高.

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.

推荐答案

创建BaseAdapter的子类应该可以正常工作.例如.拿

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;
    }
}

这篇关于如何使用SparseArray作为适配器的源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆