我正在开发一个使用 CursorAdapter 显示电话联系人的应用程序。 当我运行它时,我遇到了一个 ListView ,它只重复了一个联系人,如下所示 (“david”是我的联系人之一,只是在 ListView 中重复)
大卫 017224860
大卫 017224860
大卫 017224860
大卫 017224860
大卫 017224860
大卫 017224860 .
.
.
.
我的 Activity 看起来像
public class Contacts extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
Cursor cursor = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
startManagingCursor(cursor);
ContactCursorAdapterCT adapter= new ContactCursorAdapterCT(Contacts.this, cursor);
ListView contactLV = (ListView) findViewById(R.id.listviewblcontactsDB);
contactLV.setAdapter(adapter);
我的 cursorAdapter 看起来像:
public class ContactCursorAdapterCT extends CursorAdapter {
public ContactCursorAdapterCT(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
while (cursor.moveToNext()) {
TextView name = (TextView)view.findViewById(R.id.blacklistDB1);
name.setText(cursor.getString(cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
TextView phone = (TextView)view.findViewById(R.id.blacklistDB2);
phone.setText(cursor.getString(cursor.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.lv, parent, false);
bindView(v, context, cursor);
return v;
}
最佳答案
我注意到几点:
- CursorAdapter 为您移动 Cursor,取出您对
cursor.moveToNext()
的调用。 - 适配器的
getView()
自行调用newView()
和bindView()
;您不应该自己调用这些方法。 - 您应该观看 Android 开发者的 lectures at Google IO了解有关加速适配器的提示和技巧。提示如:
- 使用 ViewHolder,而不是重复调用
findViewById()
。 - 保存 Cursor 的索引,而不是重复调用
getColumnIndex()
。 - 获取 LayoutInflater 一次并保留本地引用。
- 使用 ViewHolder,而不是重复调用
关于android - 带有 CursorAdapter 的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13631075/