安卓適配器 baseadpter cursoradapter

CursorAdapter繼承於BaseAdapter,它是個虛類,它爲cursor和ListView提供了鏈接的橋樑。java

newView該函數第一次回調用後,若是數據增長後也會再調用,可是重繪是不會調用的。數據增長後,回調用該函數來生成與新增數據相對應的view。
bindView函數第一次回調用後,若是數據更新也會再調用,但重繪會再次調用的。
函數

添加適配器 這樣ListView就會顯示出來this

private ListView mListView;

adapter = new ConversationAdapter(this, null);
mListView.setAdapter(adapter);

CursorAdapterspa

private class ConversationAdapter extends CursorAdapter{

    private LayoutInflater inflater;  //得到上下文環境
    public ConversationAdapter(Context context, Cursor c) {
	super(context, c);
	// TODO Auto-generated constructor stub
	inflater = LayoutInflater.from(context);
    }
    
    //在適配器第一次適配時 調用的方法,一般在該方法裏 完成控件的加載
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = inflater.inflate(R.layout.conversation_item, parent, false);
        
        CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkbox);  //得到控件
        
        view.setTag(checkbox);
			
	return view;
    }

    //完成數據的綁定		
    public void bindView(View view, Context context, Cursor cursor) {
        CheckBox checkbox = (CheckBox)view.getTag();
        
        checkbox.setChecked(true); 
    }
			
}

BaseAdaptercode

將一組數據傳到像ListViewgetView()方法,它是將獲取數據後的View組件返回server

private final static int[] images = new int[]{R.drawable.a_f_inbox,R.drawable.a_f_outbox,R.drawable.a_f_sent,R.drawable.a_f_draft};
private final static int[] names = new int[]{R.string.inbox,R.string.outbox,R.string.sent,R.string.draft};

private final class FolderAdapter extends BaseAdapter{

    public int getCount() {
	return images.length;  //控件總個數 
    }

    public Object getItem(int position) {
	return names[position];  //控件的名字
    }

    public long getItemId(int position) {
	return position;   //當前控件的位置
    }

    //這裏完成得到和綁定
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
	FolderViews views = null;
	if(convertView != null){
	    view = convertView;
	    views = (FolderViews) view.getTag();
	}else{
	    view = getLayoutInflater().inflate(R.layout.folder_item, parent, false);
	    views = new FolderViews();
	    views.header = (ImageView) view.findViewById(R.id.header);
	    views.tv_name = (TextView) view.findViewById(R.id.tv_name);
	    view.setTag(views);
	}

	//綁定數據
	views.header.setImageResource(images[position]);
	views.tv_name.setText(names[position]);
	return view;
    }
			
}

private final class FolderViews{
    ImageView header;
    TextView tv_name;
}

BaseAdapter 使用ContentObserver 判斷若是發生改變,就從新查詢更新繼承

相關文章
相關標籤/搜索