问题
When I get a search result from my table, the results show up twice.

The results "a / a", "aa / aa", and "ab / a" are all correct and should be there. However, I don't want the duplicate values in the third listview entry.
Any ideas why this is happening?
Main Screen
// 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;
}
}
回答1:
Well, the problem is in your getView(int position, View convertView, ViewGroup parent)
method, because you keep adding views to the previously recycled view that listview provides you. Instead of creating a textview dynamically, you should inflate it when you create your view.
For example, to fix this:
@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;
}
回答2:
View are re-used by the adapter. So when you call
linearMain.addView(label);
It is adding multiple views into your list item every time it gets the view.
Do you really need to create a new TextView
every time and add it to your list item? I would change this this to just set the text on one existing TextView
.
来源:https://stackoverflow.com/questions/21053979/listview-duplicates-android