填充列表视图时出现问题
Trouble with populating listview
我正在尝试用自定义对象填充列表视图。我正在使用
适配器使用列表视图 class。以下是我使用适配器的代码。
adapter = new SearchListAdapter(this, values);
expListView = (ListView) findViewById(R.id.SearchList);
setListAdapter(adapter);
在 SearchListAdapter class 我有以下代码:
public class SearchListAdapter extends ArrayAdapter<String>
{
private Context context;
private ArrayList<String> values;
public SearchListAdapter(Context context, ArrayList<String> UsernameValues) {
super(context, R.layout.search_contact, UsernameValues);
this.context = context;
this.values = UsernameValues;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.search_contact, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.firstLine);
for(String Index : values)
{
textView.setText(Index);
}
return rowView;
}
}
我可以看到 setListAdapter 正在工作(我假设),因为它将信息传递到 SearchListAdapter,但是当 getView 尝试填充列表时,它只是在每个列表中输入 ArrayList 的最后一个字符串值列表中的单个元素。我缺少什么才能使每个元素都对应于 ArrayList 中的一个值?感谢您的帮助,谢谢。
您的代码
for(String Index : values)
{
textView.setText(Index);
}
实际上是迭代你的完整数据List
并在每次迭代时设置每个值。因此,在最后一次迭代之后,每个 textView
都保留了适配器支持中的最后一个值 List
。
您只需要设置与 UsernameValues
列表中 ListView
的当前行 position
相对应的值。
textView.setText(values.get(position));
我正在尝试用自定义对象填充列表视图。我正在使用 适配器使用列表视图 class。以下是我使用适配器的代码。
adapter = new SearchListAdapter(this, values);
expListView = (ListView) findViewById(R.id.SearchList);
setListAdapter(adapter);
在 SearchListAdapter class 我有以下代码:
public class SearchListAdapter extends ArrayAdapter<String>
{
private Context context;
private ArrayList<String> values;
public SearchListAdapter(Context context, ArrayList<String> UsernameValues) {
super(context, R.layout.search_contact, UsernameValues);
this.context = context;
this.values = UsernameValues;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.search_contact, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.firstLine);
for(String Index : values)
{
textView.setText(Index);
}
return rowView;
}
}
我可以看到 setListAdapter 正在工作(我假设),因为它将信息传递到 SearchListAdapter,但是当 getView 尝试填充列表时,它只是在每个列表中输入 ArrayList 的最后一个字符串值列表中的单个元素。我缺少什么才能使每个元素都对应于 ArrayList 中的一个值?感谢您的帮助,谢谢。
您的代码
for(String Index : values)
{
textView.setText(Index);
}
实际上是迭代你的完整数据List
并在每次迭代时设置每个值。因此,在最后一次迭代之后,每个 textView
都保留了适配器支持中的最后一个值 List
。
您只需要设置与 UsernameValues
列表中 ListView
的当前行 position
相对应的值。
textView.setText(values.get(position));