万能ListView适配器

来源:互联网 发布:linux 进入sql 编辑:程序博客网 时间:2024/05/16 19:10

普通的ListView适配器仅仅适应一个listview,然而一个项目中可能不止一个listview,那么,对于每一个listview都要重写一个Adapter,如果需要的listview有很多,代码量是很大的。同时,每新增一个,都要重写一个适配器,很不方便。那可不可以极大地减少代码量呢,答案当然是可以的,下面就来讲解一下:

首先,需要一个listview,代码如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <ListView        android:id="@+id/id_listview"        android:layout_width="match_parent"        android:layout_height="match_parent" /></RelativeLayout>


接着是每一项的布局文件,效果图如下:













xml文件如下,由于checkbox会抢占焦点,所以,需要对此做出处理,一种方法是在RelativeLayout中设置android:descendantFocusability="blocksDescendants",或者在CheckBox中设置android:focusable="false",android:drawableLeft="@drawable/phone"是为文字左侧添加图标。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:padding="10dip"    android:descendantFocusability="blocksDescendants"    tools:context=".MainActivity" >    <TextView        android:id="@+id/id_title"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:singleLine="true"        android:text="万能Adapter"        android:textColor="#444"        android:textSize="16sp" />        <CheckBox        android:id="@+id/id_cb"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_centerVertical="true"/>    <TextView        android:id="@+id/id_desc"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/id_title"        android:layout_marginTop="10dip"        android:layout_toLeftOf="@id/id_cb"        android:minLines="1"        android:maxLines="2"        android:text="利用抽象和封装构造万能Adapter,适配各种listview"        android:textColor="#444"        android:textSize="16sp" />    <TextView        android:id="@+id/id_time"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/id_desc"        android:layout_marginTop="6dip"        android:text="2015-8-7"        android:textColor="#444"        android:textSize="16sp" />    <TextView        android:id="@+id/id_phone"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_below="@id/id_desc"        android:layout_marginTop="6dip"        android:background="#00aa00"        android:drawableLeft="@drawable/phone"        android:text="10086"        android:textColor="#fff"        android:textSize="16sp" /></RelativeLayout>


接着实体类的创建,从listview的item中可以看出需要的元素,如下:

package com.commonadapter.bean;public class DataBean {private String title;private String desc;private String time;private String phone;private boolean isCheacked;public DataBean(String title, String desc, String time, String phone) {//super();this.title = title;this.desc = desc;this.time = time;this.phone = phone;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}public String getTime() {return time;}public void setTime(String time) {this.time = time;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public boolean getIsCheacked() {return isCheacked;}public void setIsCheacked(boolean isCheacked) {this.isCheacked = isCheacked;}}
接着是ViewHolder的抽象,包括ViewHolder的初始化,通过泛型获取获取控件,ConvertView、position的获取,最后还有普通控件通过id和需要资源设置,比如TextView、ImageView等
package com.common.adapter.utils;import android.content.Context;import android.util.SparseArray;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView;/** * ViewHolder类 * @author pmx *  */public class ViewHolder {private SparseArray<View> mViews;private int mPosition;private View mConvertView;public ViewHolder(Context context, ViewGroup parent, int layoutId,int position) {this.mPosition = position;this.mViews = new SparseArray<View>();mConvertView = LayoutInflater.from(context).inflate(layoutId, parent,false);mConvertView.setTag(this);}/** * 初始化ViewHolder * @param context * @param convertView * @param parent * @param layoutId * @param position * @return */public static ViewHolder get(Context context, View convertView,ViewGroup parent, int layoutId, int position) {if (convertView == null) {return new ViewHolder(context, parent, layoutId, position);} else {ViewHolder holder = (ViewHolder) convertView.getTag();holder.mPosition = position;return holder;}}/** * 通过viewId获取控件 *  * @param viewId * @return */@SuppressWarnings("unchecked")public <T extends View> T getView(int viewId) {View view = mViews.get(viewId);if (view == null) {view = mConvertView.findViewById(viewId);mViews.put(viewId, view);}return (T) view;}public View getmConvertView() {return mConvertView;}public int getPosition() {return mPosition;}public ViewHolder setText(int viewId,String text){TextView tv = getView(viewId);tv.setText(text);return this;}public ViewHolder setImageURI(int viewId,String url){ImageView view = getView(viewId);//Imageloader.getInstance().loadImage(view,url);return null;}}
然后是抽象成CommonAdaoter,CommonAdapter继承了BaseAdapter,其中,可以看出getView相对于传统的getView减少了很多代码,而且,相应的方法都封装在ViewHolder,而convert在MainActivity中重写:

package com.commonadapter.main;import java.util.List;import com.common.adapter.utils.ViewHolder;import com.commonadapter.bean.DataBean;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;public abstract class CommonAdapter<T> extends BaseAdapter {protected Context mContext;protected List<T> mDatas;protected LayoutInflater mInflater;private int layoutId;public CommonAdapter(Context context, List<T> datas,int layoutId) {this.mContext = context;this.mInflater = LayoutInflater.from(context);this.mDatas = datas;this.layoutId = layoutId;}@Overridepublic int getCount() {return mDatas.size();}@Overridepublic T getItem(int position) {return mDatas.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent){ViewHolder holder = ViewHolder.get(mContext, convertView, parent,layoutId, position);convert(holder,getItem(position));return holder.getmConvertView();}public abstract void convert(ViewHolder holder,T t);}
最后,MainActivity实现如下,实现以数据初始化和View的初始化,其中View初始化通过重写CommonAdapter的convert方法实现,可以看出,listview中有差别的项均通过Adapter构造方法和重写传入,而cb.setChecked(bean.getIsCheacked());和bean.setIsCheacked(cb.isChecked());是为了避免listview的复用。

package com.commonadapter.main;import java.util.ArrayList;import java.util.List;import com.common.adapter.utils.ViewHolder;import com.commonadapter.bean.DataBean;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.CheckBox;import android.widget.ListView;import android.app.Activity;public class MainActivity extends Activity {private ListView mListView;private List<DataBean> beans;// private MyAdapter mAdapter;// private MyAdapterWithCommonViewHolder myAdapterWithCommonViewHolder;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initDatas();initView();}private void initView() {mListView = (ListView) findViewById(R.id.id_listview);// mListView.setAdapter(mAdapter);// mListView.setAdapter(myAdapterWithCommonViewHolder);mListView.setAdapter(new CommonAdapter<DataBean>(MainActivity.this,beans,R.layout.item_main_list) {//private List<Integer> mPos = new ArrayList<Integer>();@Overridepublic void convert(final ViewHolder holder, final DataBean bean) {holder.setText(R.id.id_title, bean.getTitle()).setText(R.id.id_desc, bean.getDesc()).setText(R.id.id_time, bean.getTime()).setText(R.id.id_phone, bean.getPhone());final CheckBox cb = holder.getView(R.id.id_cb);cb.setChecked(bean.getIsCheacked());// cb.setChecked(false);// if(mPos.contains(holder.getPosition())){// cb.setChecked(true);// }cb.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View view) {bean.setIsCheacked(cb.isChecked());// if (cb.isChecked()) {// mPos.add(holder.getPosition());// } else {// mPos.remove((Integer)holder.getPosition());// }}});}});}private void initDatas() {beans = new ArrayList<DataBean>();DataBean bean = new DataBean("Android新技能Get1","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get2","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get3","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get4","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get5","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get6","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get7","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get8","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get9","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");bean = new DataBean("Android新技能Get0","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get3","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get4","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);bean = new DataBean("Android新技能Get5","Android打造万能ListView和GridView适配器", "2015-8-7", "10086");beans.add(bean);// mAdapter = new MyAdapter(this, beans);// myAdapterWithCommonViewHolder = new// MyAdapterWithCommonViewHolder(MainActivity.this, beans);}}






0 0
原创粉丝点击