Android:使用onClick在ListView行中更改按钮背景

我的行包含一个按钮,该按钮在我的适配器的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,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;
    }
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...