定义
适配器模式应用于数据类型转换的场景, 比如输入有无数种情况, 但是输出类型是统一的,我们可以通过Adapter返回一个统一的输出.
最典型的应用是ListView中使用的Adapter, 用户的item view各式各样, 但最终的输出都是属于view类型. ListView只需要知道getView返回的是一个View即可, 具体是什么view类型并不需要ListView关心.
代码
public class NewsAdapter extends BaseAdapter{
private List<NewsBean> mNewsBeanList;
private LayoutInflater mInflater;
public NewsAdapter(Context context, List<NewsBean> list) {
mNewsBeanList = list;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mNewsBeanList.size();
}
@Override
public Object getItem(int position) {
return mNewsBeanList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_layout, null);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
viewHolder.tvDate = (TextView) convertView.findViewById(R.id.tv_date);
viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_content);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvTitle.setText(mNewsBeanList.get(position).title);
viewHolder.tvDate.setText(mNewsBeanList.get(position).date);
viewHolder.tvContent.setText(mNewsBeanList.get(position).content);
return convertView;
}
class ViewHolder {
public TextView tvTitle;
public TextView tvDate;
public TextView tvContent;
}
}
给listView设置adapter
NewsAdapter newsAdapter = new NewsAdapter(GetJsonActivity.this, newsBeanList);
mListView.setAdapter(newsAdapter);
refer to:
https://github.com/AandK/volley_gson_demo/blob/master/src/GetJsonActivity.java
------DONE.-------