Android ListView仅按钮上的最后一行

时间:2016-02-17 19:35:48

标签: java android listview

我有以下代码:

static class ViewHolder {
    TextView camera;
    TextView players;
    TextView max_players;
    ImageView privata;
    Button Buton;
}
ViewHolder holder;
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    String variabile[] = getItem(position).split("\\s+");

    if(convertView == null)
    {
        LayoutInflater linflater = LayoutInflater.from(getContext());
        convertView = linflater.inflate(R.layout.custom_row, parent, false);
        holder = new ViewHolder();
        holder.camera = (TextView) convertView.findViewById(R.id.Nume);
        holder.players = (TextView) convertView.findViewById(R.id.players);
        holder.max_players = (TextView) convertView.findViewById(R.id.max_players);
        holder.privata = (ImageView) convertView.findViewById(R.id.privata);
        holder.Buton = (Button) convertView.findViewById(R.id.Buton);
        holder.camera.setText(variabile[0]);
        if (!variabile[1].equals("true")) {
            parola = false;
            holder.privata.setVisibility(View.INVISIBLE);
        }
        holder.players.setText(variabile[2]);
        holder.max_players.setText(variabile[3]);
        room_id = variabile[4];
        nume = variabile[5];
        holder.Buton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                hash = new HashMap<String, String>();
                hash.put("name", nume);
                hash.put("room", room_id);
                if (intra) {
                    holder.Buton.setText("Iesi");
                    site = siteul + "/join";
                    intra = false;
                } else {
                    holder.Buton.setText("Intra");
                    site = siteul + "/leave";
                    intra = true;
                }
                new ATask().execute(site);
            }
        });
        convertView.setTag(holder);
    }
    else
        holder = (ViewHolder) convertView.getTag();
    return convertView;
}

我正在尝试从PostExecute上的AsyncTask访问一行并修改它:

TextView players_mare = holder.players;
players_mare.setText(rez.substring(2));

无论按下按钮,它似乎都会修改列表中最后一项的文本视图。

1 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为您正在使用holder。渲染完成ListView后,它引用了ListView中的最后一项,因此只有最后一项才会更新,而不管单击哪个按钮的项目。您需要将单击了按钮的项目的引用传递给ATask类。

  1. 添加

    holder.Buton.setTag(holder);
    

    convertView.setTag(holder);
    

    getView()方法

  2. ATask clas中创建一个类级变量,如下所示

    ViewHolder myHolder;
    
  3. ATask

    中添加此内容
    public ATask(ViewHolder view) {
        myHolder = view;
    }
    
  4. 像这样更改ATask来电

    new ATask((ViewHolder) v.getTag()).execute(site);
    
  5. PostExecute中使用holder替换每个myHolder