如何解决ListView 正在填充相同的值
发生的情况是,我有一个 ArrayList
列表适配器代码:
package com.example.test2;
import android.content.Context;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ThreeColumn_ListAdapter extends ArrayAdapter<Pair<String,String>> {
private LayoutInflater mInflater;
private ArrayList<Pair<String,String>> news;
private int mViewResourceId;
public ThreeColumn_ListAdapter(Context context,int textViewResourceId,ArrayList<Pair<String,String>> news) {
super(context,textViewResourceId,news);
this.news = news;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = textViewResourceId;
}
public View getView(int position,View convertView,ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId,null);
TextView firstName = convertView.findViewById(R.id.textFirstName);
TextView lastName = convertView.findViewById(R.id.textLastName);
//TextView favFood = convertView.findViewById(R.id.textFavFood);
Log.i("n2",news.toString());
for(int j=0;j<news.size();j++){
firstName.setText(news.get(j).first);
lastName.setText(news.get(j).second);
}
return convertView;
}
}
ArrayList中存储的是什么
[Pair{usd -0.8068},Pair{eur 0.5327},Pair{gbp 1.2172},Pair{nzd -2.7538},Pair{cad 0.7586},Pair{aud -1.7719},Pair{chf 0.9591},Pair{jpy 1.8649}]
在列表视图布局中查看的输出:
Pair{jpy 1.8649}
在 textview 中的第一个值 firstName
迭代了 8 次,textview 中对的第二个值 lastName
迭代了 8 次,其中 8 是 ArrayList<Pair<String,String>> news
解决方法
想通了,我所要做的就是删除 for 循环并只执行 news.get(position).first 而不是为新闻做循环,因为 listview 自然会循环。
之前:
public View getView(int position,View convertView,ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId,null);
TextView firstName = convertView.findViewById(R.id.textFirstName);
TextView lastName = convertView.findViewById(R.id.textLastName);
//TextView favFood = convertView.findViewById(R.id.textFavFood);
Log.i("n2",news.toString());
for(int j=0;j<news.size();j++){
firstName.setText(news.get(j).first);
lastName.setText(news.get(j).second);
}
return convertView;
}
正确方法:
public View getView(int position,null);
TextView firstName = convertView.findViewById(R.id.textFirstName);
TextView lastName = convertView.findViewById(R.id.textLastName);
//TextView favFood = convertView.findViewById(R.id.textFavFood);
firstName.setText(news.get(position).first);
lastName.setText(news.get(position).second);
return convertView;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。