在开发中listview是每个项目必定要运用的控件,用到listview就有必要用到BaseAdapter,一般老迈搭结构的时分会把一些重用的东西抽取出来,便利每个开发人员运用而且复用性很强,那么有必要封装的好,今日简略的写一个平常运用到的,把BaseAdapter封装下,
MyBaseAdapter.java
public abstract class MyBaseAdapter extends BaseAdapter {
private List datas;
private Context context;
public MyBaseAdapter(List datas, Context context) {
super();
this.datas = datas;
this.context = context;
}
@Override
public int getCount() {
return datas.size();
}
@Override
public Object getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public abstract View getView(int position, View arg1, ViewGroup arg2);
}
其实咱们在运用adapter的时分其他三个办法 返回值都是相同的,因而这个能够在父类就处理好,仅有每个子类不知道完成的便是getView()办法的完成,因而只要让每个子类完成自己的getView()办法即可,因而就抽取成上面的MyBaseAdapter类了,现在写一个类简略有用这个结构
MainActivity.java
public class MainActivity extends Activity {
private ListView listview;
private ArrayList datas;
private LayoutInflater inflater;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listview);
inflater = LayoutInflater.from(this);
initData();
adapter = new MyAdapter(datas,this);
listview.setAdapter(adapter);
}
private void initData() {
datas = new ArrayList();
for(int i=0;i100;i++){
datas.add(测验——-);
}
}
class MyAdapter extends MyBaseAdapter{
public MyAdapter(List datas, Context context) {
super(datas, context);
}
@Override
public View getView(int position, View converView, ViewGroup arg2) {
ViewHolder holder = null;
if(converView==null){
converView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.tvContent = (TextView) converView.findViewById(R.id.tvContent);
converView.setTag(holder);
}else{
holder = (ViewHolder) converView.getTag();
}
holder.tvContent.setText(datas.get(position));
return converView;
}
class ViewHolder{
TextView tvContent;
}
}
}
其实看开源的结构仍是自己项目中的结构,一般结构都用到,接口,抽象类,接口回调,泛型,承继,内部类等,多写几遍,其实结构也没那么难