OnClick错误的项目被选中

时间:2015-12-09 05:18:10

标签: java android onitemclicklistener

我有一个列表视图,其中包含名称和手机号码作为其中的两个文本视图。 OnItemClickListener返回一个不同的项目onclick。这种情况发生的不一致 - 有时它会选择正确的项目,但有时则不会。

private void showCustomers(String json) {
        ParseCustomer parseCustomer = new ParseCustomer(json);
        parseCustomer.parseJSON();
 lv = (ListView) findViewById(R.id.list_customerInfo);
        inputSearch = (EditText) findViewById(R.id.inputSearch);
 adapter = new ArrayAdapter<String>(this,R.layout.list_customerinfo, R.id.customer_name,ParseCustomer.name);


        final List<Map<String, String>> cust = new ArrayList<Map<String, String>>();
        Map<String,String> map;
        int counter = ParseCustomer.name.length;
        for (int i=0;i<counter; i++){
            map = new HashMap<>();
            map.put("name",ParseCustomer.name[i]);
            map.put("mobile",ParseCustomer.mobile_no[i]);
            cust.add(map);
        }

        newAdapter = new SimpleAdapter(this,cust,R.layout.list_customerinfo,new String[]{"name","mobile"},new int[]{R.id.customer_name,R.id.customer_mobile});
        lv.setAdapter(newAdapter);

        inputSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                lv.setVisibility(View.INVISIBLE);

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            lv.setVisibility(View.VISIBLE);

            }

            @Override
            public void afterTextChanged(Editable s) {

                AddInvEst.this.newAdapter.getFilter().filter(s);
                lv.setVisibility(View.VISIBLE);
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map custSel = cust.get(position);
                custSelected = (String) custSel.get("name")+" "+ custSel.get("mobile");
                inputSearch.setText(custSelected);
                lv.setVisibility(View.GONE);
                Toast.makeText(AddInvEst.this, "Your selected customer is "+custSelected, Toast.LENGTH_LONG).show();
            }
        });
}

我有一个编辑文本字段,我用它来搜索或过滤列表视图。 任何人都可以发现我的错误或指导我找到更好的解决方案吗?谢谢:))

1 个答案:

答案 0 :(得分:0)

SimpleAdapter类在One to store your original List类上管理两个列表,second to store filter data. So whenever you apply filterSimpleAdapter,过滤列表的项目数量少于原始项目。

因此,在当前情况下,无论何时单击特定项目,您都会获得已过滤列表的点击位置,但您将从未过滤(原始)列表中获取项目,因此错误项目。

所以要从SimpleAdapter获取点击项目:

Map custSel = (Map) newAdapter.getItem(position);