Android入门:ListView(继承BaseAdapter实现)


任务:


从数据库中获得Person对象,通过继承BaseAdapter类,显示ListView,如下所示:

(此处我们数据库操作的代码略,因为主要讲解的是ListView)


PersonAdapter.java


package org.xiazdong.db.domain; import java.util.List; import org.xiazdong.db.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class PersonAdapter extends BaseAdapter { private List persons; //数据 private int resource; //item的布局 private Context context; private LayoutInflater inflator; private TextView nameTextView; private TextView ageTextView; private TextView idTextView; /** * * @param context mainActivity * @param persons 显示的数据 * @param resource 一个Item的布局 */ public PersonAdapter(Context context,Listpersons,int resource){ this.context = context; this.persons = persons; this.resource = resource; } /* * 获得数据总数 * */ @Override public int getCount() { return persons.size(); } /* * 根据索引为position的数据 * */ @Override public Object getItem(int position) { return persons.get(position); } /* * 根据索引值获得Item的Id * */ @Override public long getItemId(int position) { return position; } /* *通过索引值position将数据映射到视图 *convertView具有缓存功能,在第一页时为null,在第二第三....页时不为null * */ @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView==null){ inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflator.inflate(resource, null); nameTextView = (TextView)convertView.findViewById(R.id.name); //为了减少开销,则只在第一页时调用findViewById ageTextView =(TextView) convertView.findViewById(R.id.age); idTextView = (TextView)convertView.findViewById(R.id.id1); } Person person = persons.get(position); nameTextView.setText(person.getName()); idTextView.setText(person.getId()+""); ageTextView.setText(person.getAge()+""); return convertView; } }
MainActivity.java


package org.xiazdong.db; import java.util.List; import org.xiazdong.db.domain.Person; import org.xiazdong.db.domain.PersonAdapter; import org.xiazdong.db.service.DBService; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; public class MainActivity extends Activity { private ListView listView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = (ListView)this.findViewById(R.id.listview); DBService service = new DBService(this); List persons = service.pageQuery(0, 10); PersonAdapter adapter = new PersonAdapter(this,persons, R.layout.item); listView.setAdapter(adapter); } }


你可能感兴趣的:(Android入门:ListView(继承BaseAdapter实现))