ask*_*ndz 7 android listview onclick button adapter
我的行包含一个按钮,在我的适配器的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);
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我点击行位置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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4926 次 |
| 最近记录: |