如何使用SimpleCursorAdapter在Custom ListView上编写setOnItemClickListener?

时间:2015-01-19 06:43:41

标签: android listview simplecursoradapter

我是android程序的新手。我试图建立一个联系电话列表。联系电话已经完成,但是当我尝试使用intent将电话号码从列表中获取到EditText时,它总是出错。 activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/lvContacts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

$ adapter_contact_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="3dp" >

    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/txtName"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txtPhone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtName"
        android:text="@string/txtPhone"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

SampleActivity.java

public class SampleActivity extends FragmentActivity {


    private SimpleCursorAdapter adapter;
    public static final int CONTACT_LOADER_ID = 78;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupCursorAdapter();
        final ListView lvContacts = (ListView) findViewById(R.id.lvContacts);
        lvContacts.setAdapter(adapter);
        getSupportLoaderManager().initLoader(CONTACT_LOADER_ID, new Bundle(),
                contactsLoader);
        lvContacts.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                String phoneName = (String)lvContacts.getItemAtPosition(position);
                //Cursor cursor = (Cursor)lvContacts.getItemAtPosition(position);
                // Get the state's capital from this row in the database.
                //String phoneName = cursor.getString(cursor
                //      .getColumnIndexOrThrow("txtName"));
                Toast.makeText(SampleActivity.this, phoneName,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupCursorAdapter() {
        // Column data from cursor to bind views from
        String[] uiBindFrom = {
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone._ID };
        // View IDs which will have the respective column data inserted
        int[] uiBindTo = { R.id.txtName, R.id.txtPhone };
        // Create the simple cursor adapter to use for our list
        // specifying the template to inflate (item_contact),
        // Fields to bind from and to and mark the adapter as observing for
        // changes
        adapter = new SimpleCursorAdapter(this, R.layout.adapter_contact_item,
                null, uiBindFrom, uiBindTo,
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    }

    private LoaderManager.LoaderCallbacks<Cursor> contactsLoader = new LoaderManager.LoaderCallbacks<Cursor>() {
        // Create and return the actual cursor loader for the contacts data
        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            // Define the columns to retrieve
            String[] projectionFields = new String[] {
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                    ContactsContract.CommonDataKinds.Phone._ID };
            // Construct the loader
            CursorLoader cursorLoader = new CursorLoader(SampleActivity.this,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, // URI
                    projectionFields, // projection fields
                    null, // the selection criteria
                    null, // the selection args
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                            + " ASC" // the sort order
            );
            // Return the loader for use
            return cursorLoader;
        }
        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
            // The swapCursor() method assigns the new Cursor to the adapter
            adapter.swapCursor(cursor);
        }

        // This method is triggered when the loader is being reset
        // and the loader data is no longer available.
        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            // Clear the Cursor we were using with another call to the
            // swapCursor()
            adapter.swapCursor(null);
        }
    };
}

有人可以帮助解决上面的代码,所以当我点击列表视图时,我可以获得phoneNumber的值。

2 个答案:

答案 0 :(得分:1)

尝试以下代码: -

    lvContacts.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            Cursor cursor = (Cursor) adapter.getItem(position);
        }
    });

它将为您提供adapter.getItem(position)光标。现在,您可以从特定光标中获取值。

有关详细信息,请参阅以下链接: -

http://developer.android.com/reference/android/widget/CursorAdapter.html#getItem%28int

答案 1 :(得分:1)

试试这个:

String phoneName = (String) parent.getItemAtPosition(position);