我有一个listview
,它会根据arraylist
动态填充。我定义了一个自定义arrayadapter
类。该列表完全正确,只是当我将屏幕从横向旋转到纵向时,列表重复每个元素3次。以下是getView
函数的代码。
rows = (ListView)findViewByid(R.id.listview1);// in adapter constructor
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);
}
else holder = (ViewHolder) convertView.getTag();
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);
holder.dec_score.setTag(holder);
holder.inc_score.setTag(holder);
convertView.setTag(holder);
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(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position = rows.getPositionForView((View)v.getParent());
Player temp = getPlayer(position);
System.out.println("Player "+ temp.getPlayer_name() + "'s score changed");
temp.setPlayer_score(temp.getPlayer_score()-score_increment);
PlayerAdapter.this.notifyDataSetChanged();
}
});
inc.setOnClickListener(new OnClickListener(){
private Button dec;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int position = rows.getPositionForView((View)v.getParent());
Player temp = getPlayer(position);
System.out.println("Player "+ temp.getPlayer_name() + "'s score changed");
temp.setPlayer_score(temp.getPlayer_score()+score_increment);
PlayerAdapter.this.notifyDataSetChanged();
}
});
return convertView;
}
答案 0 :(得分:0)
我发现了问题。它与代码无关。需要修改清单,以便在方向更改时不会刷新活动。通过将android:configChanges="orientation"
添加到清单中的活动,它可以完美地运行。