【適配器模式的定義】:
適配器模式把一個類的接口變換成客戶民期待的另一種接口,從而使原本因接口不匹配而無法在一起工作的兩個類能夠在一起工作。
【實力類比】:
很多東西狗不喫但人喫,人喫後拉屎給狗喫屎——這個例子中的人就一個適配器!
【實戰】
public class GoodsAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Goods> goods;
public GoodsAdapter(Context context, List<Goods> girs) {
inflater = LayoutInflater.from(context);
this.goods = girs;
}
@Override
public int getCount() {
return goods.size();
}
@Override
public Object getItem(int position) {
return goods.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.item, null);
Goods g = goods.get(position);
ImageView iv_icon = (ImageView)view.findViewById(R.id.iv_icon);
iv_icon.setImageResource(g.icon);
TextView tv_lik = (TextView)view.findViewById(R.id.tv_like);
tv_lik.setText("喜歡程度:" + g.like);
TextView tv_style = (TextView)view.findViewById(R.id.tv_style);
tv_style.setText(g.style);
return view;
}
}
- GoodsAdapter是一個適配器
- 構造函數是輸入,其它函數是輸出
- 輸入的數據類型可以根據業務來設計
- 輸出的數據類型是固定的:也就是View
- 其中getView是核心函數,負責如何把輸入數據轉成輸出