我的行包含一个按钮,该按钮在我的适配器的 getView 中设置了自己的单击侦听器。我可以使用行父级中的 android:descendantFocusability="blocksDescendants" 来区分按钮点击和实际行项目点击。
当我单击按钮时,它会正确设置按钮背景,我的问题是当我滚动列表时,它也会将其设置为不同的行。我认为他们在视图回收方面存在问题。
这是我的代码:
@Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.todays_sales_favorite_row, null);
holder.favCatBtn = (Button)convertView.findViewById(R.id.favCatBtn);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.favCatBtn.setTag(position);
holder.favCatBtn.setOnClickListener(this);
return convertView;
}
@Override
public void onClick(View v) {
int pos = (Integer) v.getTag();
Log.d(TAG, "Button row pos click: " + pos);
RelativeLayout rl = (RelativeLayout)v.getParent();
holder.favCatBtn = (Button)rl.getChildAt(0);
holder.favCatBtn.setBackgroundResource(R.drawable.icon_yellow_star_large);
}
因此,如果我单击第 1 行位置的按钮,按钮背景会按预期发生变化。但当我向下滚动列表时,其他按钮也会被设置。有时,当我向上滚动到位置 1 时,按钮背景会再次恢复为原始状态。
我在这里缺少什么?我知道我就在那里,这只是我没有做的一些小事。
是的,你没看错,视图是被回收的。您将需要跟踪哪些位置已被点击并更新您的后台资源getView
方法。例如,我扩展了您的代码以添加背景切换:
private final boolean[] mHighlightedPositions = new boolean[NUM_OF_ITEMS];
@Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.todays_sales_favorite_row, null);
holder.favCatBtn = (Button)convertView.findViewById(R.id.favCatBtn);
holder.favCatBtn.setOnClickListener(this);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
holder.favCatBtn.setTag(position);
if(mHighlightedPositions[position]) {
holder.favCatBtn.setBackgroundResource(R.drawable.icon_yellow_star_large);
}else {
holder.favCatBtn.setBackgroundResource(0);
}
return convertView;
}
@Override
public void onClick(View view) {
int position = (Integer)view.getTag();
Log.d(TAG, "Button row pos click: " + position);
// Toggle background resource
RelativeLayout layout = (RelativeLayout)view.getParent();
Button button = (Button)layout.getChildAt(0);
if(mHighlightedPositions[position]) {
button.setBackgroundResource(0);
mHighlightedPositions[position] = false;
}else {
button.setBackgroundResource(R.drawable.icon_yellow_star_large);
mHighlightedPositions[position] = true;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)