我有一个listview适配器,它从数组中获取数据,并将它们放入listview中。但是,listview只显示数组中的一个项目 - 并在listview的所有行中显示它。继承我的代码,看起来有什么不对吗?
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_2, android.R.id.text1, MainActivity.values) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
TextView text2 = (TextView) view.findViewById(android.R.id.text2);
int i = 0;
int p = 0;
text1.setText(MainActivity.values[i]);
text2.setText(MainActivity.numvalues[i]);
i++;
return view;
}
};
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
答案 0 :(得分:5)
尝试替换这些行
int i = 0;
int p = 0;
text1.setText(MainActivity.values[i]);
text2.setText(MainActivity.numvalues[i]);
i++;
带
text1.setText(MainActivity.values[position]);
text2.setText(MainActivity.numvalues[position]);
每次将i的值初始化为0时,在代码中,这就是为什么你只会看到列表视图中重复该行的原因
答案 1 :(得分:3)
尝试使用position
从数组中获取值,而不是i
为每个项设置0:
text1.setText(MainActivity.values[position]);
text2.setText(MainActivity.numvalues[position]);
答案 2 :(得分:3)
你做错了。在getView
方法中,您每次都会初始化i
int i = 0;
int p = 0;
text1.setText(MainActivity.values[i]);
text2.setText(MainActivity.numvalues[i]);
i++;
更改您的代码如下
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_2, android.R.id.text1, MainActivity.values) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
TextView text2 = (TextView) view.findViewById(android.R.id.text2);
text1.setText(MainActivity.values[position]);
text2.setText(MainActivity.numvalues[position]);
return view;
}
};
listView.setAdapter(adapter);
}