【发布时间】:2018-08-08 04:53:37
【问题描述】:
请问,有人可以帮我吗?我对java编码很陌生。我正在使用 Android Studio 通过复制和粘贴来制作一些应用程序,并进行了大量的试验和错误。现在我正在编写将从MySQL 检索数据并将它们放在Listview 上的代码,但是当我向下滚动时我得到了重复的数据。近一周以来,我一直在阅读许多可以解决此问题的建议,并在我的代码上进行了尝试,但没有任何效果。因此,如果有人可以帮助我,将不胜感激。这是我的代码。
PersonAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
public class PersonAdapter extends ArrayAdapter<Person> {
public PersonAdapter(Context context, int resource,List<Person> objects) {
super(context, R.layout.item_row, objects);
}
@Override
public View getView(int position,View convertView, ViewGroup parent) {
ViewHolder viewHolder;
View view;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_row, null);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
Person p = getItem(position);
TextView textView = (TextView) convertView.findViewById(R.id.textView2);
textView.setText(p.getId());
TextView textView2 = (TextView) convertView.findViewById(R.id.textView);
textView2.setText(p.getName());
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
static class ViewHolder {
public TextView textView;
public TextView textView2;
public TextView textView3;
public Button addbutt;
public Button delbutt;
public ViewHolder(View convertView) {
textView = (TextView) convertView.findViewById(R.id.textView);
textView2 = (TextView) convertView.findViewById(R.id.textView2);
textView3 = (TextView) convertView.findViewById(R.id.textView3);
addbutt = (Button) convertView.findViewById(R.id.addbutt);
delbutt = (Button) convertView.findViewById(R.id.delbutt);
}
}
Person.java
public class Person {
private String name;
private String id;
public Person(String name, String id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
【问题讨论】:
-
您的视图持有者模式错误。如果您使用视图支架模式,则不需要在
getView()内使用findViewById()。检查这个 StackOverflow answer 以获得关于视图持有者模式的正确想法。
标签: android listview arraylist duplicates