如何从Android中的ArrayList填充的列表视图中选择多个项目

时间:2014-09-15 08:56:03

标签: android listview arraylist

我正在尝试编写一个程序来选择列表视图中的多个项目。但我很难选择多个项目。请让我知道怎么做。贝娄是我如何填充Arraylist,我有一个带复选框的自定义行。我需要在按钮点击事件中获取所选项目(名称,编号)。先感谢您。我试图理解其他帖子,但由于我无法将它们与我的代码联系起来,我不知道该怎么做。

public class Contactselect extends Activity {

    ListView lv;
    EditText et;
    int count;
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    String phoneNumber;
    String name;

    String Name = "Contact";
    String Phone = "Phonenumber";

    TextWatcher search;
    SimpleAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);

        listcontacts();

        lv = (ListView) findViewById(R.id.contactlist);
        lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE);
        lv.setTextFilterEnabled(true);
        adapter = new SimpleAdapter(this, list, R.layout.row, new String[] {
                Name, Phone }, new int[] { R.id.names, R.id.numbers });

        lv.setAdapter(adapter);

        Button b = (Button) findViewById(R.id.done);
        b.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {

                String selected = "";
                int cntChoice = lv.getCount();

                SparseBooleanArray sparseBooleanArray = lv
                        .getCheckedItemPositions();
                for (int i = 0; i < cntChoice; i++) {
                    if (sparseBooleanArray.get(i)) {
                        selected += lv.getItemAtPosition(i).toString() + "\n";

                    }

                }

                Toast.makeText(Contactselect.this, selected, Toast.LENGTH_LONG)
                        .show();

            }
        });

        et = (EditText) findViewById(R.id.search);
        et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub
                Contactselect.this.adapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub

            }
        });

    }

    private ArrayList<HashMap<String, String>> listcontacts() {
        // TODO Auto-generated method stub
        FileInputStream fis = null;
        try {
            fis = openFileInput("contacts.xml");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            XmlPullParserFactory factory;

            factory = XmlPullParserFactory.newInstance();

            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(new InputStreamReader(fis));
            int eventType = parser.getEventType();
            int o = 0;
            while (eventType != XmlPullParser.END_DOCUMENT) {

                HashMap<String, String> map = new HashMap<String, String>();

                // set flags for main tags.
                if (eventType == XmlPullParser.START_DOCUMENT) {

                } else if (eventType == XmlPullParser.START_TAG) {
                    String tag_name = parser.getName();
                    if (tag_name.contains("contacts")) {
                        // Log.i("tag",
                        // "name"
                        // + String.valueOf(parser
                        // .getAttributeValue(0))
                        // + "......................"
                        // + "number"
                        // + String.valueOf(parser
                        // .getAttributeValue(1)));
                        name = String.valueOf(parser.getAttributeValue(0));
                        phoneNumber = String.valueOf(parser
                                .getAttributeValue(1));

                        Log.i(name, phoneNumber);
                        map.put(Name, name);
                        map.put(Phone, phoneNumber);

                        list.add(map);
                        count++;

                    }
                }
                try {
                    eventType = parser.next();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Log.i("End document", "Ended" + count);
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

}

1 个答案:

答案 0 :(得分:1)

请尝试这种方式,希望这有助于您解决问题。

public class Contactselect extends Activity {

    private ListView lv;
    private EditText et;
    private Button b;
    private int count;
    private String Name = "Contact";
    private String Phone = "Phonenumber";
    private String IsSelected = "isSelected";
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

    private ContactAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.contactlist);
        lv.setTextFilterEnabled(true);
        et = (EditText) findViewById(R.id.search);
        b = (Button) findViewById(R.id.done);

        listcontacts();
        adapter  = new ContactAdapter(this,list);
        lv.setAdapter(adapter);


        b.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                String selected = "";
                for (HashMap<String,String> row : list){
                    if(row.get(IsSelected).equals("true")){
                        selected += row.get(Name) + "\n";
                    }
                }
                Toast.makeText(Contactselect.this, selected, Toast.LENGTH_LONG)
                        .show();

            }
        });


        et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,int arg3) {
                adapter.filter(cs.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {

            }
        });
    }

    private void listcontacts() {
        FileInputStream fis = null;
        try {
            fis = openFileInput("contacts.xml");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            XmlPullParserFactory factory;

            factory = XmlPullParserFactory.newInstance();

            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(new InputStreamReader(fis));
            int eventType = parser.getEventType();
            int o = 0;
            while (eventType != XmlPullParser.END_DOCUMENT) {

                HashMap<String, String> map = new HashMap<String, String>();

                // set flags for main tags.
                if (eventType == XmlPullParser.START_DOCUMENT) {

                } else if (eventType == XmlPullParser.START_TAG) {
                    String tag_name = parser.getName();
                    if (tag_name.contains("contacts")) {
                        // Log.i("tag",
                        // "name"
                        // + String.valueOf(parser
                        // .getAttributeValue(0))
                        // + "......................"
                        // + "number"
                        // + String.valueOf(parser
                        // .getAttributeValue(1)));
                        Log.i(name, phoneNumber);
                        map.put(Name, String.valueOf(parser.getAttributeValue(0)));
                        map.put(Phone, String.valueOf(parser
                                .getAttributeValue(1)));
                        map.put(IsSelected,"false");

                        list.add(map);
                        count++;

                    }
                }
                try {
                    eventType = parser.next();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Log.i("End document", "Ended" + count);
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
    }

    class ContactAdapter extends BaseAdapter {

        private Context context;
        private ArrayList<HashMap<String,String>> contacts;

        public ContactAdapter(Context context,ArrayList<HashMap<String,String>> contacts) {
            this.context =context;
            this.contacts =new ArrayList<HashMap<String, String>>();
            this.contacts.addAll(contacts);

        }

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

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

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

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;

            if (convertView == null) {
                holder      = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.row, null);
                holder.name      = (TextView) convertView.findViewById(R.id.name);
                holder.numbers   = (TextView) convertView.findViewById(R.id.numbers);
                holder.checkbox      = (CheckBox) convertView.findViewById(R.id.checkbox);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.name.setText(contacts.get(position).get(Name));
            holder.numbers.setText(contacts.get(position).get(Phone));
            holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton ButtonView, boolean isChecked) {
                    contacts.get(position).put(IsSelected, "" + isChecked);
                    for (HashMap<String,String> data : list){
                        if(data.get(Name).equals(contacts.get(position).get(Name))){
                            data.put(IsSelected,contacts.get(position).get(IsSelected));
                            break;
                        }
                    }
                    notifyDataSetChanged();

                }
            });

            if (contacts.get(position).get(IsSelected).toString().equals("false")) {
                holder.checkbox.setChecked(false);
            } else {
                holder.checkbox.setChecked(true);
            }

            return convertView;
        }

        public void filter(String charText) {
            contacts.clear();
            if (charText.length() == 0) {
                contacts.addAll(list);
            } else {
                for (HashMap<String,String> contact : list) {
                    if (contact.get(Name).toLowerCase().contains(charText.toLowerCase())) {
                        contacts.add(contact);
                    }
                }
            }
            notifyDataSetChanged();
        }


        class ViewHolder {
            TextView  name;
            TextView  number;
            CheckBox checkbox;
        }
    }
}