我有一个充气行列表,其中包含两个TextView和两个按钮。按钮应增加/减少其中一个textViews。但是,当我尝试实现它时,我无法从onclickListener中获取正确的标记。它给出了一个空指针异常。我有一个holder和convertview实现,Holder确实为convertview设置了标签。更具体地说,我需要能够获取convertview的标记以更改行的值。
我把星星放在我认为重要的部分旁边。
这是适配器代码
class PlayerAdapter extends ArrayAdapter<Player> {
private ArrayList<Player> players;
private Context cont;
private Player temp;
public Player getTemp() {
return temp;
}
public void setTemp(Player temp) {
this.temp = temp;
}
public Player getItem(int index){
return players.get(index);
}
public PlayerAdapter(Context context, int layoutId, int textViewResourceId, ArrayList<Player> items) {
super(context,layoutId, textViewResourceId, items);
players = items;
cont = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater =getLayoutInflater();
convertView = inflater.inflate(R.layout.player_slot,null);
holder = new ViewHolder(convertView, position);
holder.player_name = (TextView) convertView.findViewById(R.id.name);
holder.player_score = (TextView) convertView.findViewById(R.id.score);
holder.dec_score = (Button) convertView.findViewById(R.id.decrement);
holder.inc_score = (Button) convertView.findViewById(R.id.increment);
convertView.setTag(holder);
}
else holder = (ViewHolder) convertView.getTag();
Button dec = (Button)convertView.findViewById(R.id.decrement);
Button inc =(Button)convertView.findViewById(R.id.increment);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView score = (TextView)convertView.findViewById(R.id.score);
System.out.println("tag = " +dec.getTag());
Player temp = getPlayer(position);
System.out.println(temp.getPlayer_name() + temp.getPlayer_score());
if(temp != null){
//holder.player_name.setText(temp.getPlayer_name());
//holder.player_score.setText(""+temp.getPlayer_score());
name.setText(temp.getPlayer_name());
score.setText(""+temp.getPlayer_score());
}
dec.setOnClickListener(new OnClickListener(){
private Button dec;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position = (Integer) ((View)v.getParent()).getTag();//***
Player temp = getPlayer(position);
System.out.println("Player "+ temp.getPlayer_name() + "'s score changed");
temp.setPlayer_score(temp.getPlayer_score()-1);//**
PlayerAdapter.this.notifyDataSetChanged();
}
});
return convertView;
}
}