单击 ListView 上的侦听器

Posted

技术标签:

【中文标题】单击 ListView 上的侦听器【英文标题】:Click Listener on ListView 【发布时间】:2011-07-07 10:44:17 【问题描述】:

我已从 SDK 页面修改了此示例,以从手机中获取所有联系人组并显示它们。但是,我无法弄清楚如何单击其中一个,然后使用 Groups._ID 执行其他操作。有人可以教我如何在此列表中获得点击/选择侦听器吗?

MyListAdapter.java

package com.example.simplelist;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.Groups;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

public class MyListAdapter extends ListActivity 

    @Override
    protected void onCreate(Bundle savedInstanceState)
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_list_activity_view);
        Cursor mCursor = this.getContentResolver().query(Groups.CONTENT_URI, null, null, null, null);
        startManagingCursor(mCursor);
        ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, mCursor, new String[] Groups.NAME, Groups._ID, new int[] android.R.id.text1, android.R.id.text2);
        setListAdapter(adapter);
    

custom_list_activity_view.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="vertical"
         android:layout_
         android:layout_
         android:paddingLeft="8dp"
         android:paddingRight="8dp">

     <ListView android:id="@id/android:list"
               android:layout_
               android:layout_
               android:background="#00FF00"
               android:layout_weight="1"
               android:drawSelectorOnTop="false" android:choiceMode="singleChoice" android:clickable="true" />

     <TextView android:id="@id/android:empty"
               android:layout_
               android:layout_
               android:background="#FF0000"
               android:text="No data"/>
 </LinearLayout>

two_line_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_
     android:layout_
     android:orientation="vertical">

     <TextView android:id="@+id/text1"
         android:textSize="16sp"
         android:textStyle="bold"
         android:layout_
         android:layout_/>

     <TextView android:id="@+id/text2"
         android:textSize="16sp"
         android:layout_
         android:layout_/>
 </LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.simplelist"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="3" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MyListAdapter"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.READ_CONTACTS" />
</manifest>

【问题讨论】:

【参考方案1】:

这应该允许您以您想要的方式与选定的项目进行交互。

MyListAdapter.java

package com.example.simplelist;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.Groups;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MyListAdapter extends ListActivity 

    List<ContactGroup> groups = new ArrayList<ContactGroup>(); 

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

        this.groups = getContacts();
        ContactGroupAdapter cAdapter = new ContactGroupAdapter(this); 
        setListAdapter(cAdapter);
    

    private List<ContactGroup> getContacts()
        List<ContactGroup> grps = new ArrayList<ContactGroup>();
        ContentResolver cr = getContentResolver();
        Cursor groupCur = cr.query(Groups.CONTENT_URI, null, null, null, null);
        if (groupCur.getCount() > 0) 
            while (groupCur.moveToNext()) 
                ContactGroup newGroup = new ContactGroup();
                newGroup.Id = groupCur.getString(groupCur.getColumnIndex(Groups._ID));
                newGroup.Name = groupCur.getString(groupCur.getColumnIndex(Groups.NAME));
                grps.add(newGroup);
            
        
        return grps;
    

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) 
        ContactGroup selectedGroup = new ContactGroup();
        selectedGroup = groups.get(position);
        Toast.makeText(getBaseContext(), selectedGroup.Name + " ID #" + selectedGroup.Id, 1).show();
    


    public class ContactGroupAdapter extends BaseAdapter
        public ContactGroupAdapter(Context c) 
            mContext = c;
        
        @Override
        public int getCount() 
            return groups.size();
        

        @Override
        public Object getItem(int position) 
            return position;
        

        @Override
        public long getItemId(int position) 
            return position;
        

        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
            ViewHolder holder;
            if(convertView == null)
                LayoutInflater vi = LayoutInflater.from(this.mContext);  
                convertView = vi.inflate(R.layout.two_line_list_item, null);
                holder = new ViewHolder();
                convertView.setTag(holder); 
            
            else 
                //Get view holder back
                holder = (ViewHolder) convertView.getTag();
            
            ContactGroup c = groups.get(position);
            if (c != null) 
                //Name
                holder.toptext = (TextView) convertView.findViewById(R.id.text1);
                holder.toptext.setText(c.Name);
                //ID
                holder.bottomtext = (TextView) convertView.findViewById(R.id.text2);
                holder.bottomtext.setText(c.Id);
            
            return convertView;
        
        private Context mContext;

    
    public static class ViewHolder 
        TextView toptext;
        TextView bottomtext;
    

    public class ContactGroup
        public String Id;
        public String Name;
    


two_line_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01" android:layout_ 
    android:layout_ xmlns:android="http://schemas.android.com/apk/res/android">

         <TextView android:id="@+id/text1"
         android:textSize="16sp"
         android:textStyle="bold"
         android:layout_
         android:layout_/>

     <TextView android:id="@+id/text2"
         android:textSize="16sp"
         android:layout_
         android:layout_/>

</LinearLayout>

【讨论】:

谢谢分享。我一直在寻找这个很长一段时间=)【参考方案2】:

由于您使用的是 ListActivity,您需要覆盖 onListItemClick()。

protected void onListItemClick(ListView l, View v, int position, long id) 
    // position is the position in the adapter and id is what adapter.getItemId() returns.
    // use one of them to get the group id from the data.

【讨论】:

无论我点击哪里都会返回 android.content.ContentResolver$CursorWrapperInner@45a04508。我做了吐司;) +1 因为这是答案的 1/2。因为无论我在哪里单击,我都将数据绑定到光标,所以我得到的是光标而不是项目。如果我通过迭代生成列表并使用适配器添加它们,那么您的答案就完美了。 @Bill Mote 因为您使用的是光标,所以我认为您必须执行 mCursor.moveToPosition(position) 之类的操作。很高兴您成功了!

以上是关于单击 ListView 上的侦听器的主要内容,如果未能解决你的问题,请参考以下文章

ListView Intent On Item 单击侦听器停止应用程序错误

如何在android中去listview适配器项目点击监听器片段?

片段内 Listview 中动态视图的 onClick 侦听器

类上的 JavaScript 单击事件侦听器

OnItemClick 侦听器和单击的 View 项的可见性

ListView 中的 RadioButton 波纹效果