问题
I have a list view whose adapter is in a different class in a different package. Now I have to get the data from database then I set Adapter for my list view using this data. So I have created an ArryList and pass this in the constructor of Adapter while seeting it for the list view. But the problem is that the data is repeating. eg.- there are 12 distinct Strings in the arraylist but what I get is -first five elements in order and after that the same five are being repeated. The count of data is always right but the position will always be 0,1,2,3,4 . I can not understand what the problem is . here is the code -
public class CheckboxAdapter extends BaseAdapter{
LayoutInflater inflater ;
ArrayList<String> mData = new ArrayList<String>();
//constructor for lesion adapter
public CheckboxAdapter (Context context, ArrayList<String> data){
inflater = LayoutInflater.from(context);
mData = data;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mData.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
Log.v("pos", ""+position);
convertView = inflater.inflate(R.layout.e_lesion_liststyle, null);
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.disease_lesion_checkbox);
cb.setText(mData.get(position));
cb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
cb.setButtonDrawable(R.drawable.check_box_1);
}
});
}//end of if condition
return convertView;
}
回答1:
try this.. just write all code out of the condition expect inflate code..
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
Log.v("pos", ""+position);
convertView = inflater.inflate(R.layout.e_lesion_liststyle, null);
} //end of if condition
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.disease_lesion_checkbox);
cb.setText(mData.get(position));
cb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
cb.setButtonDrawable(R.drawable.check_box_1);
}
});
return convertView;
}
来源:https://stackoverflow.com/questions/7359356/data-repeating-in-android-list-view