ListView
<ListView android:id="@+id/lv" android:layout_width="match_parent" android:layout_height="match_parent" />
item_list.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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"> <TextView android:id="@+id/item" android:layout_width="match_parent" android:layout_height="45dp" android:gravity="center_vertical" tools:text="2015年10月22日 周四" /> </LinearLayout>
适配器MyAdapter继承基类MyBaseAdapter(WeekBean查看android日期工具类)
import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.xh.boke.R; import com.xh.boke.base.BaseActivity; import com.xh.boke.base.MyBaseAdapter; import com.xh.boke.bean.WeekBean; import com.xh.boke.holder.ViewHolder; import java.util.List; /** * 测试Adapter * Created by Administrator on 2015/10/22 0022. */ public class MyAdapter extends MyBaseAdapter<WeekBean> { private TextView tv; public MyAdapter(BaseActivity context, List<WeekBean> list) { super(context, list); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) convertView = LayoutInflater.from(mContext).inflate(R.layout.item_list, null); try { tv = ViewHolder.get(convertView, R.id.item); } catch (IllegalAccessException e) { e.printStackTrace(); } WeekBean bean = datas.get(position); tv.setText(bean.year+"年"+bean.month+"月"+bean.day+"日"+" "+bean.weeks); return convertView; } }
功能优化之ViewHolder类
/** * view临时存储器 * Created by Administrator on 2015/10/22 0022. */ import android.util.SparseArray; import android.view.View; public class ViewHolder { /** * 获取参数convertView中的指定id资源 * @param convertView 实例化之后的convertView,不为空指针 * @param id 指定id资源 * @return 在convertView中的与id对应的view * @throws IllegalAccessException 当convertView为空时,抛出 */ @SuppressWarnings("unchecked") public static <T extends View> T get(View convertView, int id) throws IllegalAccessException { if(convertView == null) throw new IllegalAccessException("convertView can not be null"); SparseArray<View> viewHolder = (SparseArray<View>) convertView.getTag(); if (viewHolder == null) { viewHolder = new SparseArray<View>(); convertView.setTag(viewHolder); } View childView = viewHolder.get(id); if (childView == null) { childView = convertView.findViewById(id); viewHolder.put(id, childView); } return (T) childView; } }
在activity中使用
ListView lv = (ListView) findViewById(R.id.lv); List<WeekBean> list = getWeekDate();//查看android日期工具类 MyAdapter adapter = new MyAdapter(this,list); lv.setAdapter(adapter);