0

我正在使用自定义适配器,每行都有使用创建的按钮数量,

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = (HorizontalScrollView) inflater.inflate(
            R.layout.hrowlayout, parent, false);
LinearLayout ll1 = (LinearLayout) rowview.findViewById(R.id.ll);    
Button[] b = new Button[M];     
    for (int i = 0; i < M; i++) {
        b[i] = new Button(ll1.getContext());
        b[i].setText(....);
        LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams( x, 90);
        b[i].setLayoutParams(param2);
        ll1.addView(b[i],params2);
        }
 return rowview;   
}

我的问题是如何在此适配器上使用 ViewHolder 以及如何标记不在 XML 文件中的按钮 .. 即在

b[i] = new Button[M];
4

2 回答 2

1

ViewHolder 模式中的 ViewHolder 是一个愚蠢的对象,它只保存对视图内容的引用,以避免重复使用 inflate() 和 findViewById(),因此您可以将 Button 数组与其他任何您想要的东西一起粘贴到 ViewHolder来参考。

像这样的事情就是你要做的。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    ViewHolder holder;
    if(convertView == null){//if we haven't already created a view
        //inflate a new view
        View rowview = (HorizontalScrollView) inflater.inflate(
        R.layout.hrowlayout, parent, false);
        LinearLayout ll1 = (LinearLayout) rowview.findViewById(R.id.ll);

        Button[] b = new Button[M];     

        for (int i = 0; i < M; i++) {
            b[i] = new Button(ll1.getContext());
            b[i].setText(....);
            LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams( x, 90);
            b[i].setLayoutParams(param2);
            ll1.addView(b[i],params2);
        }

        convertView = rowview;
        holder = new ViewHolder();
        holder.buttons = b;
        convertView.setTag(viewHolder);
    }

    holder = convertView.getTag()
    for(Button button : holder.buttons){
        //do something
    }


    return convertView;   
}

和视图持有人

class ViewHolder{
    Button [] buttons;
    //other things
}
于 2013-05-23T11:11:50.993 回答
0

您可以在查看器本身中清除您的按钮数组

public static class viewHolder{
    Button[] b;
}

getView你可以使用holder.b=new Button[4];

于 2013-05-23T11:08:42.800 回答