总结:
1- 在MainActivity中只放数据,加载适配器
2- 单独定义实体类
3- 自定义适配器,并与实体类相关联,在适配器里写优化的代码将视图与数据相关联
MainActivity
2- News.java
3- BaseAdapterDAO.java
package com.example.cycle_toolbar_drawer.BaseAdapter; import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView; import com.example.cycle_toolbar_drawer.R; import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater; /**
* Created by Administrator on 2016/5/26 0026.
*添加数据的baseAdapter实现类
*/
public class BaseAdapterDAO extends BaseAdapter {
//通过构造方法获取数据源中的数据,与适配器关联起来
private List<News> mNews;
private LayoutInflater mLayoutInflater; public BaseAdapterDAO(Context context,List<News> news){
mNews = news;
//context要使用当前的Adapter的界面对象mLayoutInflater布局装载器对象
mLayoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mNews.size();
}
@Override
public Object getItem(int i) {
return mNews.get(i);
} @Override
public long getItemId(int i) {
return i;
} @Override
public View getView(int i, View view, ViewGroup viewGroup) { //2- 定义ViewHolder
ViewHolder viewHolder;
if (view == null) {
//3- 实例化ViewHolder 并且适配ViewHolder中的三个参数
viewHolder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.content_listview_linear, null);
viewHolder.ViewHolder_imageView = (ImageView) view.findViewById(R.id.content_listView_imageView);
viewHolder.ViewHolder_title = (TextView) view.findViewById(R.id.content_listView_Title);
viewHolder.ViewHolder_content = (TextView) view.findViewById(R.id.content_listView_Content); //4- 通过setTag将ViewHolder与view相关联
view.setTag(viewHolder);
}else {
//5- 当不为空的时候直接通过getTag方法找到控件
viewHolder = (ViewHolder) view.getTag();
}
News newsItem = mNews.get(i);
viewHolder.ViewHolder_imageView.setImageResource(newsItem.getItem_image_Resource_id());
viewHolder.ViewHolder_title.setText(newsItem.getItem_Title());
viewHolder.ViewHolder_content.setText(newsItem.getItem_Content()); return view; /* 普通方式
ImageView content_listView_imageView = (ImageView) view.findViewById(R.id.content_listView_imageView);
TextView content_listView_Title = (TextView) view.findViewById(R.id.content_listView_Title);
TextView content_listView_Content = (TextView) view.findViewById(R.id.content_listView_Content); News newsItem = mNews.get(i);
content_listView_imageView.setImageResource(newsItem.getItem_image_Resource_id());
content_listView_Title.setText(newsItem.getItem_Title());
content_listView_Content.setText(newsItem.getItem_Content());
return view;*/
}
// 文艺式 ——避免通过findViewById找内容而浪费资源和时间 //1- 创建内部类ViewHolder
class ViewHolder{
public ImageView ViewHolder_imageView;
public TextView ViewHolder_title;
public TextView ViewHolder_content;
}
}