2012-05-27 70 views
1
Cursor c = managedQuery(People.CONTENT_URI,null,null,null,People.NAME); 
String[] cols = new String[]{People.NAME}; 
int[] views = new int[]{android.R.id.text1}; 
SimpleCursorAdapter sca = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,c,cols,views); 
listview.setAdapter(adapter); 

我正在使用此代碼段將ListViewCursor連接起來。Simplecursoradapter的工作

我要問

String[] cols = new String[]{People.NAME}; 
int[] views = new int[]{android.R.id.text1}; 

究竟?

,並請有關SimpleCursorAdapter

回答

0

這是一個映射,告訴適配器哪一列從你的光標使用來填充佈局中的小部件。

它們按給定的順序使用。 from數組中列出的第一列中的數據(您稱之爲cols)將進入數組中列出的第一個id(您稱它爲views),依此類推。

其他參數是包含您在數組中指定的視圖ID和包含要在數組中使用的數據的遊標的佈局。

0

list_item.xml的構造所需的參數解釋請參閱本LINK

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:padding="10dp" 
    android:textSize="16sp" > 
</TextView> 

HelloListView.java

public class HelloListView extends ListActivity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, getNames())); 

    ListView lv = getListView(); 
    lv.setTextFilterEnabled(true); 

    lv.setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> parent, View view, 
     int position, long id) { 
     // When clicked, show a toast with the TextView text 
     Toast.makeText(getApplicationContext(), ((TextView) view).getText(), 
      Toast.LENGTH_SHORT).show(); 
    } 
    }); 
} 
private ArrayList<String> getNames(){ 
     ArrayList<String> namesArray = new ArrayList<String>(); 
     Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 
     ContentResolver cr = getContentResolver(); 
     Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 
     String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}; 
     Cursor names = getContentResolver().query(uri, projection, null, null, null); 

     int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 
     names.moveToFirst(); 
     do { 
      namesArray.add(names.getString(indexName)); 
     } while (names.moveToNext()); 
     return namesArray; 
    } 
}