如何检索名称|列表视图中的多个已检查项的值对?

时间:2015-01-30 19:13:57

标签: android listview

我的列表视图工作正常并填充游标中的所有项目。 我需要在列表视图中指定获取指定名称的ID。 我使用多个复选框从列表视图中选择项目。 如何从列表视图中获取所选项目的名称|值对?

   ListView listView;
    ArrayAdapter<String> adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        try
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.servicelist_item);

        //String[] sports ;


        //get jobtype 
        Cursor cur=dbHelper.fetchByJobNumber(stringJobnumber);
        String cur_type;
        cur_type=cur.getString(18);

        //passing jobtype to fetch service items through cursor
        Cursor cursor=dbHelper.fetchItemsByType(cur_type);
        ArrayList<String> sports=new ArrayList<String>();
        if (cursor.moveToFirst()) 
        {
           do 
           {
               //assigning cursor items to arraylist variable sports
              /* assigning item name to list view*/
              /*My cursor holds name value pair */
               sports.add(cursor.getString(3)); 
           } 
           while (cursor.moveToNext());
        }



        //setting array adapter to populate listView
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, sports);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setAdapter(adapter);

        button.setOnClickListener(this);
    }
    catch(Exception e)
    {
        System.out.println(e);
    }

   }

// Onclick方法

 public void onClick(View v) 
    {
        SparseBooleanArray checked = listView.getCheckedItemPositions();
        ArrayList<String> selectedItems = new ArrayList<String>();
        for (int i = 0; i < checked.size(); i++) 
        {
            // Item position in adapter
            int position = checked.keyAt(i);
            // Add sport if it is checked i.e.) == TRUE!
            if (checked.valueAt(i))
                selectedItems.add(adapter.getItem(position));
        }

        final String[] outputStrArr = new String[selectedItems.size()];
        Log.e("selectedItems.size()====>>", ""+selectedItems.size());
        for (int i = 0; i < selectedItems.size(); i++) 
        {
            Log.e("selectedItems====>>", ""+selectedItems.get(i));
            outputStrArr[i] = selectedItems.get(i);
        } 
    }

1 个答案:

答案 0 :(得分:0)

查看你的代码,我会创建一个包含你的名字和id的对象:

public class Sport {
     private String id;
     private String name;
     public Sport(String id, String name){
        this.id = id;
        this.name = name;
     }

     public String getId(){
         return id;
     }

     public String getName(){
         return name;
      }
}

我经常需要此功能,因此我所做的是创建一个自定义适配器,其中包含String[]个ID和List<T>数据,以及地图<String, T>。这样做会给你的列表提供一些很好的功能,比如通过id和position访问。如果此适配器将维护3个数据实例,我建议仅将其用于相对较小(小于100)的列表。

这是我喜欢使用的适配器:

public abstract class MappedAdapter<T> extends BaseAdapter{

    private Context mContext;
    private Map<String, T> mMap;
    private ArrayList<String> mIdList;

    public MappedAdapter(Context context, ArrayList<T> arrayList) {
        this.mContext = context;
        mMap = new HashMap<>();
        mIdList = new ArrayList<>();
        for (T object : arrayList) {
            add(object);
        }
    }

    public MappedAdapter(Context context, T[] arrayList){
        this.mContext = context;
        mMap = new HashMap<>();
        mIdList = new ArrayList<>();
        for (T object : arrayList) {
            add(object);
        }
    }

    public abstract String getObjectId(T object);

    public abstract String getObjectString(T object);

    public T getObject(int position) {
        return mMap.get(mIdList.get(position));
    }

    public String getObjectId(int position){
        return mIdList.get(position);
    }

    public boolean add(T object) {
        final String id = getObjectId(object);
        if(!mMap.containsKey(id)){
            mIdList.add(id);
            mMap.put(id, object);
            this.notifyDataSetChanged();
            return true;
        }
        return false;
    }

    public void remove(T object){
        final String id = getObjectId(object);
        mIdList.remove(id);
        mMap.remove(id);
        this.notifyDataSetChanged();
    }

     @SuppressWarnings("unchecked")
    public Map.Entry<String, T> getEntry(int position){
         HashMap<String, T> entry = new HashMap<>();
         String key = mIdList.get(position);
         entry.put(key, mMap.get(key));
         return (Map.Entry<String, T>) entry;
     }

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

    @Override
    public Object getItem(int position) {
        return mMap.get(mIdList.get(position));
    }

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

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        T object = mMap.get(mIdList.get(position));
        if (view == null) {
            int layoutResource = android.R.layout.simple_list_item_1;
            view = LayoutInflater.from(mContext).inflate(layoutResource, null);
        }
        TextView tv = (TextView) view.findViewById(android.R.id.text1);
        tv.setText(getObjectString(object));
        return view;
    }
}

这是一个我使用很多的适配器类,你只需要在列表中传递,你可以通过id和position访问它。并且不允许重复的对象。它需要通用,因此您可以将它用于许多不同的对象。

这将要求您覆盖两种方法:

  1. getObjectId()对象ID是用作构建地图的id / key的对象。
  2. getObjectString() objectString是您要在列表视图中显示的字符串
  3. 默认情况下,这将使用android.R.layout.simple_list_item_1进行布局。显然,你可以改变它,或者更好的是,构建一个子类并覆盖getView()


    用法:

       MappedAdapter<Sport> mappedAdapter = new MappedAdapter<Sport>(context, sports){
            @Override
            public String getObjectId(Sport object) {
                return object.getId();
            }
    
            @Override
            public String getObjectString(Sport object) {
                return object.getName();
            }
        };
    
        ListView listView =  ... ;
        listView.setAdapter(mappedAdapter);
    

    要获得您的Key | Value对,您可以按位置获取它:

       Map.Entry<String, Sport> entry = mappedAdapter.getEntry(positon);
       String key = entry.getKey();
       Sport sport = entry.getValue();
    

    如果您需要任何澄清,请与我们联系。很乐意提供帮助。