如何从ListView项目获取文本?

时间:2015-07-13 12:29:23

标签: java android

我有一个包含人名和电话号码的listView。这个想法是打电话给那个名字被点击的人,但是我无法弄清楚如何从ListView中获取人数。 这是我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_kaikki_numerot);

    // create a cursor to query the Contacts on the device to start populating a listview
    cursor1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    startManagingCursor(cursor1);

    String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID}; // get the list items for the listadapter could be TITLE or URI


    int[] to = {android.R.id.text1, android.R.id.text2}; // sets the items from above string to listview

    // new listadapter, created to use android checked template
    SimpleCursorAdapter listadapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor1, from, to);


    setListAdapter(listadapter);


    lv = getListView();
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            //here is the onClick where you should be able to make call

        }
    });
}

提前致谢

3 个答案:

答案 0 :(得分:1)

      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
             {
                 String data=(String)arg0.getItemAtPosition(arg2);

                 //Let data= "item1 item2 item3" for example:
                  String[] parts = data.split(" ");
                  String part1 = parts[0]; // item1
                  String part2 = parts[1]; // item2

             }});

data包含您点击的位置数据。做你想做的事情

答案 1 :(得分:0)

您可以使用position中的setOnItemClickListener对象。使用此position获取cursor1

中的数据

答案 2 :(得分:0)

试试这个......

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            //here is the onClick where you should be able to make call
            String person_number = ((TextView) view.findViewById(android.R.id.text2)).getText().toString();
        }
    });