我是Android新手,并在youtube上关注了slidenerd的教程。这是我的代码。出于某种原因,它崩溃而没有出错。它适用于Android的常规适配器,但自定义适配器不起作用。请帮忙。感谢。
public List<String> teamsList = new ArrayList<String>();
public List<String> teamCities = new ArrayList<String>();
public List<String> teamDates = new ArrayList<String>();
mListView = (ListView) findViewById(R.id.teamsList);
mListView.setAdapter(new TeamsAdapter(this, teamsList, teamCities, teamDates));
class SingleRow {
String team;
String city;
String date;
public SingleRow(String team, String city, String date) {
this.team = team;
this.city = city;
this.date = date;
}
}
class TeamsAdapter extends BaseAdapter {
public ArrayList<SingleRow> list;
Context c;
public TeamsAdapter(Context c, List<String> teamsList, List<String> teamCities, List<String> teamDates) {
this.c = c;
list = new ArrayList<SingleRow>();
String[] teams = teamsList.toArray(new String[teamsList.size()]);
String[] cities = teamCities.toArray(new String[teamCities.size()]);
String[] dates = teamDates.toArray(new String[teamDates.size()]);
for (int i=0;i<teams.length;i++) {
list.add(new SingleRow(teams[i], cities[i], dates[i]));
}
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.team_row, parent, false);
TextView team = (TextView) row.findViewById(R.id.team);
TextView city = (TextView) row.findViewById(R.id.city);
TextView date = (TextView) row.findViewById(R.id.date);
SingleRow temp = list.get(position);
team.setText(temp.team);
city.setText(temp.city);
date.setText(temp.date);
return row;
}
}
答案 0 :(得分:0)
可能是inflater。如果您正在使用Activity,请尝试在TeamsAdapter的构造函数中传递LayoutInflater而不是Context。
public TeamsAdapter(LayoutInflater inflater, List<String> teamsList, List<String> teamCities, List<String> teamDates)
{
this.mInflater = inflater;
...
}
在你的getView函数中:
View row = mInflater.inflate(R.layout.team_row, parent, false);
在您实例化TeamsAdapter的代码中,我假设它是一个Activity派生类,请执行以下操作:
teamsAdapter = new TeamsAdapter(this.getLayoutInflater(), ...);
答案 1 :(得分:0)
为什么要将单元格视图扩展到父视图组?
View row = inflater.inflate(R.layout.team_row, null, false);
尝试使用null,我不确定这是否是问题。
答案 2 :(得分:0)
考虑到你问题的当前内容,继续我的猜测:
第一次适配器视图调用getView时(调用setAdapter时),convertview参数始终为null。所以,你不能从那个arg得到一个布局inflater。将其更改为使用LayoutInflater.from(Context context)
方法,而不是使用parent.getContext()作为上下文。像,
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext)
...
继续前进,这里有一篇关于如何很好地做适配器的文章。 http://developer.android.com/training/improving-layouts/smooth-scrolling.html
HTHS