2015-10-25 6 views
0

Я после этого API руководство здесь: http://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViewsЗаполнение SimpleCursorAdapter с данными

Это фрагмент кода из приведенной выше ссылке:

String[] fromColumns = {ContactsContract.Data.DISPLAY_NAME, 
         ContactsContract.CommonDataKinds.Phone.NUMBER}; 
int[] toViews = {R.id.display_name, R.id.phone_number}; 

Мой вопрос .. что R.id.display_name и R.id.phone_number на макете и как это определить в макете .xml? Как это связано с контейнером listView?

Кроме того, как указано имя R.layout.person_name_and_number, как показано ниже?

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
     R.layout.person_name_and_number, cursor, fromColumns, toViews, 0); 
ListView listView = getListView(); 
listView.setAdapter(adapter); 

Спасибо.

+0

Сделано окончательное обновление моего ответа. Надеюсь, вам понравится :) – ProblemSlover

+0

Большое спасибо! Я тщательно рассмотрю его. –

+0

Я только что добавил разрешение на чтение строк. в противном случае ваше приложение будет аварийно завершено, когда вы попытаетесь запустить приложение, используя код, указанный в ответе. Пожалуйста, отметьте это – ProblemSlover

ответ

1

В соответствии с документированной исходный код конструктора

SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags)

/** 
* Standard constructor. 
* 
* @param context The context where the ListView associated with this 
*   SimpleListItemFactory is running 
* @param layout resource identifier of a layout file that defines the views 
*   for this list item. The layout file should include at least 
*   those named views defined in "toViews" 
* @param c The database cursor. Can be null if the cursor is not available yet. 
* @param from A list of column names representing the data to bind to the UI. Can be null 
*   if the cursor is not available yet. 
* @param toViews that should display column in the "from" parameter. 
*   These should all be TextViews. The first N views in this list 
*   are given the values of the first N columns in the from 
*   parameter. Can be null if the cursor is not available yet. 
* @param flags Flags used to determine the behavior of the adapter, 
* as per {@link CursorAdapter#CursorAdapter(Context, Cursor, int)}. 
*/ 

Поэтому макет person_name_and_number.xml должен включать в себя 2 TextViews .. с идентификатором R.id.display_name, R.id.phone_number, как показано ниже

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" > 
    <TextView 
     android:id="@+id/display_name" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textSize="28dip" /> 
     <TextView 
     android:id="@+id/phone_number" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textSize="28dip" /> 
</LinearLayout> 

Ваш список макет my_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" > 
    <ListView 
     android:id="@android:id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" /> 
</LinearLayout> 

Так что ваша деятельность может быть определена следующим образом

   public class MyListActivity extends ListActivity { 

         @Override 
         public void onCreate(Bundle savedInstance) { 
          setContentView(R.layout.my_layout); 


        String[] columnsForCursor = new String[] { 
    ContactsContract.Data._id, ContactsContract.Data.DISPLAY_NAME, 
ContactsContract.CommonDataKinds.Phone.NUMBER }; 

          Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,columnsForCursor, null, null, null); 
        int[] toViews = new int[] { R.id.display_name, R.id.phone_number }; 

        String[] columnsForView = new String[]{ ContactsContract.Data.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER 
}; 
          SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.list_example_entry, cursor, columnsForView, toViews); 

          ListView listView = getListView(); 

          setListAdapter(mAdapter); 
         } 
       } 

Это не обязательно, чтобы расширить деятельность с ListActivity. Можно просто инициализировать объект ListView, определенный в макете следующим

  public class MyActivity extends Activity { 

       ListView mListView; 
       SimpleCursorAdapter mAdapter; 
        @Override 
        public void onCreate(Bundle savedInstance) { 
         setContentView(R.layout.my_layout); 

       String[] columnsForCursor = new String[] { 
ContactsContract.Data._id, ContactsContract.Data.DISPLAY_NAME,     ContactsContract.CommonDataKinds.Phone.NUMBER }; 
         Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, columnsForCursor, null, null, null); 

         int[] toViews = new int[] { R.id.display_name, R.id.phone_number }; 

         String[] columnsForView = new String[]{ ContactsContract.Data.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER }; 
         mAdapter = new SimpleCursorAdapter(this, R.layout.list_example_entry, cursor, columns, toViews); 

         mListView = (ListView) findViewById(R.id.my_listView); 
         mListView.setListAdapter(mAdapter); 
        } // On Create 
      } // MyActivity 

Update: для того, чтобы воспроизвести примеры кода выше, ваше приложение должно иметь READ_CONTACTS разрешения. Чтобы запросить это, добавьте этот элемент в ваш файл манифеста в качестве дочернего элемента из <manifest>

<uses-permission android:name="android.permission.READ_CONTACTS" /> 
+0

Для идентификатора ListView мне интересно, если это опечатка, или если принято считать ее как @ android: id/android: list. Из ссылок в Интернете это может быть @ android: id/list или @ id/android: list. http://stackoverflow.com/questions/16948981/id-androidlist-vs-androidid-list-in-android-layout-xml –

+0

Это типично :) Спасибо за указание! – ProblemSlover

+1

Как вы сказали Это должно быть @android: id/list .. Я отредактирую свой ответ через минуту – ProblemSlover

Смежные вопросы