我有一个带有自定义适配器的列表视图。自定义适配器只是 TextView 和 2 个 ImageButtons。单击 ImageButton 时,我希望它的图像切换。但是,这有效,当我向下滚动时,一些随机项目也会被切换。
所以我认为这与屏幕上项目位置的相对性有关。所以我为每个 ImageButton 分配了一个标签,它对应于它在列表视图中的位置。然后我使用以下代码正确选择必要的项目:
int firstVisiblePos = listView.getFirstVisiblePosition();
int viewPos = 0;
int position = Integer.parseInt(v.getTag().toString());
Toast.makeText(this, v.getTag().toString(), Toast.LENGTH_SHORT).show();
for (int i = 0; i < listView.getChildCount(); i++) {
viewPos = firstVisiblePos + i;
if (viewPos == position) {
relativeLayout = (RelativeLayout) listView.getChildAt(position);
break;
}
}
但是我仍然遇到相同的行为。任何帮助表示赞赏。
升级版:
public class CustomAdapter extends BaseAdapter {
private ArrayList<String> data;
private Activity myActivity;
private LayoutInflater inflater;
public CustomAdapter(Activity activity, ArrayList<String> data) {
this.myActivity = activity;
this.data = data;
this.inflater = (LayoutInflater) myActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row, null);
}
TextView proverb = (TextView) convertView.findViewById(R.id.title);
proverb.setText(data.get(position));
proverb.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 14);
proverb.setTypeface(MainActivity.tf, 1);
ImageButton favBtn = (ImageButton) convertView.findViewById(R.id.btn_favorite);
if(MainActivity.favorites.contains(data.get(position))){
// favorite, set fav icon
favBtn.setImageDrawable(myActivity.getResources().getDrawable(R.drawable.fav));
}
favBtn.setTag(position);
return convertView;
}
}