ListView
适配器入门:
private ListView lv;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
lv = (ListView) findViewById(R.id.list_view);
lv.setAdapter(adapter);
adapter.add("hello");
adapter.add("world");
适配器深入
在MainActivity:
private ListView lv;
private ArrayAdapter<ListCellData> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<ListCellData>(this,android.R.layout.simple_list_item_1);
// adapter = new ArrayAdapter<String>(this,R.layout.list_cell);
lv = (ListView) findViewById(R.id.list_view);
lv.setAdapter(adapter);
adapter.add(new ListCellData("小米","男",17));
adapter.add(new ListCellData("小那","女",16));
// adapter.add("hello");
// adapter.add("world");
lv.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
ListCellData data = adapter.getItem(position);
Toast.makeText(this, String.format("名字:%s,性别:%s,年龄:%s",
data.getUserName(),data.getSex(),data.getAge()),
Toast.LENGTH_SHORT).show();
}
在ListCellData.java:
package com.example.wonchuang.usinglistview;
public class ListCellData {
public ListCellData(String userName,String sex,int age){
this.userName = userName;
this.sex = sex;
this.age = age;
}
private String userName="小丽";
private String sex="女";
private int age=0;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return getUserName();
}
}