有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java记住选定的ListView项

我是安卓新手,我有以下问题

我有一个列表视图。ListView由ArrayList中的数据填充。我在每一行添加了一个复选框

单击“Resume按钮”后,我想将所选项目写入SQLliteDB(db工作正常——我用静态数据对其进行了测试)

我现在的问题是: 如何从列表中获取选中的项目

谢谢大家的帮助! 顺致敬意, 基普


共 (2) 个答案

  1. # 1 楼答案

    可以使用此ListView方法getCheckedItemPositions()获取所有选中的位置。确保ListView中的子视图实际实现了Checkable接口,否则复选标记信息将不会传递给ListView

  2. # 2 楼答案

    但我自己想出来了。 我只想通过点击复选框视图来选择行

    我修改了我的自定义阵列适配器

    这是我的代码:

    public class ContactAdapter extends ArrayAdapter<Contact> implements OnClickListener{
    
    private static HashMap<Integer, Boolean> teamItems = new HashMap<Integer, Boolean>();
    int count = 0;
    
    private List<Contact> items;
    private int mode;
    
    CheckBox add_to_team;
    static int counter = 3;
    
    public ContactAdapter(Context context, int textViewResourceId, List<Contact> objects, int mode) {
        super(context, textViewResourceId, objects);
        // TODO Auto-generated constructor stub
        this.context = context;
        this.mode = mode;
        this.items = objects;
    }
    
    @Override
    public View getView(int position, View convertView, final ViewGroup parent) {
        View v = convertView;
    
        if(v == null) {
            //get a reference to the LayoutInflator
            LayoutInflater li = (LayoutInflater)getContext()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            //and inflate our XML into the View
            v = li.inflate(R.layout.list_contacts_item, null);
        }
    
        String race = items.get(position).race;
        String nick = items.get(position).nick;
        String name = items.get(position).name;
        final int pos = position;
    
        if(v!= null) {
            // Do the work for the other views
    
            // MODE 1 = SELECTION-MODE  
            if(mode == 1) {
    
                add_to_team.setVisibility(0);
    
                try {
                    if(count!=0) {
                        boolean b = teamItems.get(pos);
                        if(b==false) {
                            add_to_team.setChecked(false);
                        }
                        else {
                            add_to_team.setChecked(true);
                        }
                    }
                } catch (NullPointerException e) {
    
                }
    
                add_to_team.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                        teamItems.put(pos, arg1);
                        count++;
                    }
                });
            } else {
                add_to_team.setVisibility(8);
            }
        }
        return v;
    }   
    

    }

    我添加了一个HashMap,在其中保存所选项目。我可以通过调用HashMap从我的活动中调用select状态。。。而且效果很好