我有以下代码:
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));
无论按下按钮,它似乎都会修改列表中最后一项的文本视图。
答案 0 :(得分:0)
这种情况正在发生,因为您正在使用holder
。渲染完成ListView
后,它引用了ListView
中的最后一项,因此只有最后一项才会更新,而不管单击哪个按钮的项目。您需要将单击了按钮的项目的引用传递给ATask
类。
添加
holder.Buton.setTag(holder);
后
convertView.setTag(holder);
在getView()
方法
在ATask
clas中创建一个类级变量,如下所示
ViewHolder myHolder;
在ATask
public ATask(ViewHolder view) {
myHolder = view;
}
像这样更改ATask
来电
new ATask((ViewHolder) v.getTag()).execute(site);
在PostExecute
中使用holder
替换每个myHolder