android 簡(jiǎn)單的adapter封裝
在開發(fā)中l(wèi)istview是每個(gè)項(xiàng)目肯定要使用的控件,用到listview就必須用到BaseAdapter,一般老大搭框架的時(shí)候會(huì)把一些重用的東西抽取出來(lái),方便每個(gè)開發(fā)人員使用并且復(fù)用性很強(qiáng),那么必須封裝的好,今天簡(jiǎn)單的寫一個(gè)平時(shí)使用到的,把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);
}
其實(shí)我們?cè)谑褂胊dapter的時(shí)候其他三個(gè)方法 返回值都是一樣的,因此這個(gè)可以在父類就處理好,唯一每個(gè)子類不知道實(shí)現(xiàn)的就是getView()方法的實(shí)現(xiàn),因此只要讓每個(gè)子類實(shí)現(xiàn)自己的getView()方法即可,因此就抽取成上面的MyBaseAdapter類了,現(xiàn)在寫一個(gè)類簡(jiǎn)單實(shí)用這個(gè)框架
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;i<100;i++){
datas.add("測(cè)試-------");
}
}
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;
}
}
}
其實(shí)看開源的框架還是自己項(xiàng)目中的框架,一般框架都用到,接口,抽象類,接口回調(diào),泛型,繼承,內(nèi)部類等,多寫幾遍,其實(shí)框架也沒那么難