我已经完成解析 json 并将其获取到 ListView ,但是我遇到了问题当单击 listview 中的项目时仅显示最后解析的 Json 数据时,我确切地希望单击该项目时按位置显示正确的数据:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
final String fname = c.getString("fname");
final String lname = c.getString("lname");
String username = c.getString("username");
//String user_id = c.getString("user_id");
//String gender = c.getString("gender");
HashMap<String, String> contact = new HashMap<>();
contact.put("fname", fname);
contact.put("lname", lname);
contact.put("username", username);
users.add(contact);
ListAdapter adapter = new SimpleAdapter(FindPeopleActivity.this, users,
R.layout.list_item, new String[]{"fname", "lname", "username"},
new int[]{R.id.fname, R.id.lname, R.id.username});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent , View view , int position , long id){
Intent i = new Intent(FindPeopleActivity.this,UserProfileActivity.class);
Toast.makeText(getApplicationContext(),fname,Toast.LENGTH_SHORT).show();
}
});
}
最佳答案
在for循环之后设置setOnItemClickListener。
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//i = row/item clicked in listview
//Get the variable from the array you passed to the adapter
newItem.variable1 = jsonArrayData[i].variable1;
newItem.variable2 = jsonArrayData[i].variable2;
//Pass the selected json info...
yourMethod(newItem);
Toast.makeText(getApplicationContext(),fname,Toast.LENGTH_SHORT)
.show();
}
});
在您的 toast 中放入一些测试值,例如 i 来查看正在传递的值。
关于java - (onItemClick) 显示 ListView 中的 Json 数据 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46269870/