从Listview获取View到String

时间:2015-02-21 16:43:15

标签: java android regex string listview

我有一个Listview,当我点击List视图时,我需要获取每行的String值。

这是我的代码

public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

try {
    JSONObject jsonResponse = new JSONObject(jsonResult);
    JSONArray jsonMainNode = jsonResponse.optJSONArray("lectureraccount");

    for (int i = 0; i < jsonMainNode.length(); i++) {
        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
        String name = jsonChildNode.optString("lecturerName");
        String code = jsonChildNode.optString("lecturerCode");
        String outPut = name + "   ---   " + code;
        employeeList.add(createEmployee("lecturer", outPut));
    }
} catch (JSONException e) {
    Toast.makeText(getApplicationContext(), "Error" + e.toString(),
            Toast.LENGTH_SHORT).show();
}

SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,android.R.layout.simple_list_item_1,new String[] { "lecturer" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,int position, long id)
    {
        String str = parent.getAdapter().getItem(position).toString();
        System.out.println(str);
    }});
}

托管以获得这样的输出。

{lecturer=MAGESWARY A/P MUNIANDI   ---   C-MAGESWARY}

我的问题是如何获得这样的输出

C-MAGESWARY

多数民众赞成。我是编程新手,不太了解。我是否需要完全更改我的代码。如果是,怎么样? 谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用split方法中的onItemClick执行此操作,如下所示:

String str = parent.getAdapter().getItem(position).toString();
String[] parts = str.split("---");
String part1 = parts[0]; 
String part2 = parts[1]; // This is the part you want
String output = part2.replaceAll("\\s+","") //trim whitespace
String output2 = output.replace("}", ""); // remove the "}" character
System.out.println(output2);

输出:

C-MAGESWARY

答案 1 :(得分:0)

这是一个Java问题。查看链接Class String Oracle。除了前面的答案,请查看方法substring,indexOf和lastIndexof。 由于您可以控制ListView中的字符串格式,因此您可以轻松自己。只需在示例“C-MAGESWARY”之前添加唯一字符,例如“!@”。然后,您可以在字符串中搜索这些字符。请记住这种技术用于未来的应用程序。