Android ListView Adapter

来源:互联网 发布:网络竞速游戏排行榜 编辑:程序博客网 时间:2024/04/28 07:29

这段时间,由于在项目中经常要用到ListView控件,所以对ListView控件的自定义做了一些了解 ,其实listView控件的使用关键是adapter的使用

直接上代码

package com.Adapters;import java.util.ArrayList;import java.util.HashMap;import com.AppClient.R;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;public class RecipeAdapter extends BaseAdapter{private LayoutInflater layoutInflater;      private Context context;        /** * 构造函数,配置参数 * @param data 配置ArrayList<HashMap<String,Object>类型的参数> * @param context this*/public RecipeAdapter(ArrayList<HashMap<String, Object>> data, Context context) {super();this.data = data;this.layoutInflater = layoutInflater.from(context);this.context = context;}private ArrayList<HashMap<String, Object>> data;      /**      * LayoutInflater 类是代码实现中获取布局文件的主要形式      *LayoutInflater layoutInflater = LayoutInflater.from(context);      *View convertView = layoutInflater.inflate();      *LayoutInflater的使用,在实际开发种LayoutInflater这个类还是非常有用的,它的作用类似于 findViewById(),                   不同点是LayoutInflater是用来找layout下xml布局文件,并且实例化!                 而findViewById()是找具体xml下的具体 widget控件(如:Button,TextView等)。      */                @Overridepublic int getCount() {// TODO Auto-generated method stubreturn data.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn data.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}     /**      * android绘制每一列的时候,都会调用这个方法      */ @Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubControlors controlor=null;if(convertView==null){controlor=new Controlors();//获取布局组件convertView=layoutInflater.inflate(R.layout.recipe_list, null);controlor.imageView=(ImageView)convertView.findViewById(R.id.recipe_image);controlor.textView=(TextView)convertView.findViewById(R.id.recipe_name);controlor.writer=(TextView)convertView.findViewById(R.id.writer);controlor.mainResource=(TextView)convertView.findViewById(R.id.main_resource);controlor.littleResourc=(TextView)convertView.findViewById(R.id.little_resource);//使用tag来存储数据convertView.setTag(controlor);}else{controlor=(Controlors)convertView.getTag();}//绑定数据以及事件触发controlor.imageView.setBackgroundResource((Integer)data.get(position).get("recipe_image"));controlor.textView.setText((String)data.get(position).get("recipe_name"));    controlor.writer.setText((String)data.get(position).get("writer"));    controlor.mainResource.setText((String)data.get(position).get("main_resource"));    controlor.littleResourc.setText((String)data.get(position).get("little_resource"));return convertView;}}


原创粉丝点击