这里我有一个来自url的解析json数据并添加到具有搜索功能的listview中。当通过搜索功能获取项目时,setOnItemClickListener不能从listview获得正确的位置项,但是没有搜索功能的OnItemClick工作正常。
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json_data = jArray.getJSONObject(i);
final String fname = json_data.getString("fname");
final String lname = json_data.getString("lname");
final String username = json_data.getString("username");
final String gender = json_data.getString("gender");
HashMap<String, String> contact = new HashMap<>();
contact.put("fname", fname);
contact.put("lname", lname);
contact.put("username", username);
contact.put("gender", gender);
users.add(contact);
simpleAdapter = new SimpleAdapter(SearchActivity.this, users,
R.layout.list_search_item, new String[]{"fname","lname"},
new int[]{R.id.fname,R.id.lname});
lv.setAdapter(simpleAdapter);
lv.setTextFilterEnabled(true);
Search.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
SearchActivity.this.simpleAdapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable arg0) {
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent , View view , int position , long id){
Intent i = new Intent(SearchActivity.this,UserProfileActivity.class);
i.putExtra("fname",users.get(position).get("fname"));
i.putExtra("lname",users.get(position).get("lname"));
i.putExtra("username",users.get(position).get("username"));
i.putExtra("gender",users.get(position).get("gender"));
startActivity(i);
}
});
}