当我从表格中获得搜索结果时,结果会显示两次。
结果“a / a”,“aa / aa”和“ab / a”都是正确的,应该在那里。但是,我不希望第三个listview条目中的重复值。
为什么会发生这种情况?
主屏幕
// Set up search array
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
CustomAdapter
public class CustomAdapter extends ArrayAdapter<InventoryItem> {
Context context;
int layoutResourceId;
LinearLayout linearMain;
ArrayList<InventoryItem> data = new ArrayList<InventoryItem>();
public CustomAdapter(Context context, int layoutResourceId,
ArrayList<InventoryItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
linearMain = (LinearLayout) row.findViewById(R.id.lineraMain);
}
InventoryItem myItem = data.get(position);
TextView label = new TextView(context);
label.setText(myItem.details);
linearMain.addView(label);
return row;
}
}
答案 0 :(得分:8)
嗯,问题出在您的getView(int position, View convertView, ViewGroup parent)
方法中,因为您一直在为listview提供的以前回收的视图添加视图。您应该在创建视图时对其进行充气,而不是动态创建文本视图。
例如,要解决此问题:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
//Make sure the textview exists in this xml
} else {
row = convertView;
}
InventoryItem myItem = data.get(position);
TextView label = (Textview) row.findViewById(R.id.YOU_TEXT_VIEW_ID);
label.setText(myItem.details);
return row;
}
答案 1 :(得分:0)
适配器重新使用视图。所以当你打电话时
linearMain.addView(label);
每次获取视图时,它都会在列表项中添加多个视图。
您是否真的需要每次都创建一个新的TextView
并将其添加到您的列表项?我会将此更改为仅在现有TextView
上设置文本。