Android开发时,当用ListView显示列表化内容,似乎并不能实现下拉显示后面更多的内容,或者之后的内容要开辟新的ListView,先前的不能重复利用,浪费资源,此处用BaseAdapter解决此问题:
此处,用显示简易的书籍列表做样例
先定义book类
public class Book {
private String name,anthor;
private double price;
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Book(String name, String anthor, double price) {
super();
this.name = name;
this.anthor = anthor;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAnthor() {
return anthor;
}
public void setAnthor(String anthor) {
this.anthor = anthor;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
//导入各种包
public class Anli extends Activity {
List<Book> booklist =new ArrayList<Book>();
ListView list;
void fill()//填入各种书籍名称,这里随便
{
booklist.add(new Book("C语言","啦啦啦",23));
booklist.add(new Book("CC语言","啦啦啦",25));
booklist.add(new Book("CCC语言","啦啦啦",243));
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.anli);
fill();
list=(ListView)findViewById(R.id.listbook);
list.setAdapter(new MyAdapter());//设置适配器
}
class MyAdapter extends BaseAdapter
{
@Override
public int getCount() {
// TODO Auto-generated method stub
return booklist.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override //重写getView方法
public View getView(int position, View convertView, ViewGroup parent) {
View row= convertView;
Wrapper www = null;
if(row==null)
{
//如果为空,做解析,不能直接用
row=LayoutInflater.from(Anli.this).inflate(R.layout.anli2, parent, false);
//将布局文件解析为view好资源,如果不为空,就不解析,重复利用
www=new Wrapper(row);
row.setTag(www);
}
else
{
www=(Wrapper)row.getTag();
}
//会重复,要修改
TextView bookname=www.getBookname();
TextView bookanthor=www.getBookauthor();
TextView bookprice=www.getBookprice();
Book book=booklist.get(position);
bookname.setText(book.getName());
bookanthor.setText(book.getAnthor());
bookprice.setText(book.getPrice()+"");
return row;
}
}//MyAdapter
class Wrapper
{
TextView bookname;
TextView bookanthor;
TextView bookprice;
View row;
public Wrapper(View row)
{
this.row=row;
}
public TextView getBookname()
{
if(bookname==null)
{
//如果为空,查找
TextView bookname=(TextView) row.findViewById(R.id.bookname);
}
return bookname;
}
public TextView getBookauthor()
{
if(bookanthor==null)
{
//如果为空,查找
TextView bookanthor=(TextView) row.findViewById(R.id.bookauthor);
}
return bookanthor;
}
public TextView getBookprice()
{
if(bookprice==null)
{
//如果为空,查找
TextView bookprice=(TextView) row.findViewById(R.id.bookpricec);
}
return bookprice;
}
}//wrapper
}