第一种,使用simple adapter
simpleadapter 是最简单的一种方式,但是其数据源必须是map类型。
1.生成 SimpleAdapter()对象
2.设置数据源
3.设置每个item的布局
4.设置SimpleAdapter(Context context, //上下文
List extends Map
int resource, //每个item的布局
String[] from,//map的key
int[] to) //相应控件的id
5.为listview绑定SimpleAdapter
接下来看代码:
public class User {
private String userName;
private int userRank;
public User(String userName, int userRank) {
super();
this.userName = userName;
this.userRank = userRank;
}
public User(){
super();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserRank() {
return userRank;
}
public void setUserRank(int userRank) {
this.userRank = userRank;
}
}
public class RankingActivity extends Activity {
//数据源
ArrayList al = new ArrayList();
private ListView ls_rank;
List
第二种:BaseAdapter
1.创建一个MyBaseAdapter,重写四个方法
class MyBaseAdapter extends BaseAdapter {
@Override
public int getCount() {
return al.size();
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View row = view;
Wrapper wrapper;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.rank_list_item, viewGroup, false);
wrapper = new Wrapper(row);
row.setTag(wrapper);
} else {
wrapper = (Wrapper) row.getTag();
}
TextView tvName = wrapper.gettvName();
TextView tvRank = wrapper.gettvRank();
tvName.setText(al.get(i).getUserName());
tvRank.setText(al.get(i).getUserRank()+"");
return row;
}
}
class Wrapper {
private TextView tvName;
private TextView tvRank;
private View row;
public Wrapper(View row) {
this.row = row;
}
public TextView gettvName() {
if (tvName == null) {
tvName = (TextView) row.findViewById(R.id.tv_name);
}
return tvName;
}
public TextView gettvRank() {
if (tvRank == null) {
tvRank = (TextView) row.findViewById(R.id.tv_rank);
}
return tvRank;
}
}
然后在onCreate里面绑定adapter就可以了
效果如上所示
三:ArrayAdapter,新建一个MyArrayAdapter 重写getView方法
class MyArrayAdapter extends ArrayAdapter{
public MyArrayAdapter(@NonNull Context context, @LayoutRes int resource, @IdRes int textViewResourceId, @NonNull List objects) {
super(context, 0, 0, objects);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View row = convertView;
Wrapper wrapper;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.rank_list_item, parent, false);
wrapper = new Wrapper(row);
row.setTag(wrapper);
} else {
wrapper = (Wrapper) row.getTag();
}
TextView tvName = wrapper.gettvName();
TextView tvRank = wrapper.gettvRank();
tvName.setText(al.get(position).getUserName());
tvRank.setText(al.get(position).getUserRank()+"");
return row;
}
}
三种方法完成了