热门IT资讯网

BaseAdapter

发表于:2024-11-29 作者:热门IT资讯网编辑
编辑最后更新 2024年11月29日,package com.example.testlist;import java.util.ArrayList;import java.util.HashMap;import java.util.Li
package com.example.testlist;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;import android.app.Activity;import android.content.Context;import android.graphics.Color;public class MainActivity extends Activity implements OnItemClickListener{private MyAdapter adapter;private List> list;private ListView listView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView = (ListView) findViewById(R.id.listView1);// 取得控件listView.setOnItemClickListener(this);list = getData();// 获取数据adapter = new MyAdapter(this);listView.setAdapter(adapter);}private List> getData(){list = new ArrayList>();Map map;for(int i=0; i<2; i++){map = new HashMap();map.put("title", "title" + i);map.put("img", R.drawable.ic_launcher);list.add(map);}return list;}public void add(View v){Map map;map = new HashMap();map.put("title", "title" + 100);map.put("img", R.drawable.ic_launcher);list.add(map);adapter.notifyDataSetChanged();}// ViewHolder静态类static class ViewHolder {public ImageView img;public TextView title;}public class MyAdapter extends BaseAdapter {private LayoutInflater mInflater = null;private MyAdapter(Context context) {// 根据context上下文加载布局this.mInflater = LayoutInflater.from(context);}@Overridepublic int getCount() {// 在此适配器中所代表的数据集中的条目数return list.size();}@Overridepublic Object getItem(int position) {// 获取数据集中与指定索引对应的数据项return position;}@Overridepublic long getItemId(int position) {// 获取在列表中与指定索引对应的行idreturn position;}// 获取一个在数据集中指定索引的视图来显示数据@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder = null;// 如果缓存convertView为空,则需要创建Viewif (convertView == null) {holder = new ViewHolder();// 根据自定义的Item布局加载布局convertView = mInflater.inflate(R.layout.item, null);holder.title = (TextView) convertView.findViewById(R.id.textView1);holder.img = (ImageView) convertView.findViewById(R.id.p_w_picpathView1);// 将设置好的布局保存到缓存中,并将其设置在Tag里,以便后面方便取出TagconvertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}holder.title.setText((String) list.get(position).get("title"));holder.img.setBackgroundResource((Integer) list.get(position).get("img"));return convertView;}}@Overridepublic void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {Toast.makeText(MainActivity.this, "" + arg2, Toast.LENGTH_SHORT).show();}}//item.xml        //activity_main.xml            
0