Android BaseAdapter

来源:互联网 发布:iphone通话录音软件 编辑:程序博客网 时间:2024/04/29 19:09

在Android应用开发中,列表显示是经常会碰到的功能。开发列表显示功能离不开Adapter类。一般比较简单的列表功能使用SimpleAdapter就能完成了。比较复杂的话,就需要自定义Adapter类,在自定义的Adapter类中要具体实现BaseAdapter类中的一些方法。

1.自定义Adapter类的成员

一般来说,自定义的Adapter类必要的成员有:

LayoutInflater对象,作为用来获取、设置一个ListView项的UI的桥梁;

(构造函数中:inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

getView方法中:

if (convertView == null) {
    convertView = inflater.inflate(R.layout.list_item, null);
}
TextView text = (TextView) convertView.findViewById(R.id.list_item_text);

List<data>对象,保存需要呈现的数据。

2.自定义Adapter类的构造函数:

public ListViewAdapter(Context context,List<String> items){
    if(items==null){
        items=new ArrayList<String>();
    }else{
        this.items=items;

    }

    inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}


3.公共方法:

//获取数据项数

public int getCount(){

}

//获取数据集合中某一位置的数据对象

public Object getItem(int position) {

}

//设置一个数据项的UI呈现形式和显示内容

public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.list_item, null);
    } 

    TextView text = (TextView) convertView.findViewById(R.id.list_item_text);
    //下面就可以设置ListView中每一项的内容和UI了
}


使用SimpleAdapter:

一条原始数据使用HashMap保存,整体则是一个ArrayList<HashMap>。

ListView.setAdapter(new SimpleAdapter(Context, HashMap列表, 数据项的layout, new String[]{HashMap中的键列表}, new int[]{数据项的layout中用来显示数据的控件id列表}));

原创粉丝点击