package com.softeem.phone;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ListViewCompat;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView list;
private ArrayList arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
arrayList=new ArrayList<>();
list.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrayList));
readContacts(); //這裡是先配置的適配器,再往arraylist中添加內容的。為啥還能正確顯示數據(也就是說頁面顯示了readContacts()執行後的數據)剛開始
List中不應該是空的?然後頁面上顯示空才對呀 }
private void readContacts() {
Cursor cur=null;
try {
cur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
int i=0;
while(cur.moveToNext())
{
i++;
if(i>7)
break;
String name = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
arrayList.add(name);
}
} finally {
if(cur!=null)
cur.close();
}
}
}
你調用list.setAdapte並把List數據傳入後,你後面更新了List數據,Adapter也會去自動刷新的(觀察者模式)。
但是最後調用下notifyDataSetChange方法去刷新數據