我有一个包含在片段中的 ListView。当在列表视图上单击一个项目时,我希望它执行一些代码,但执行的代码取决于单击列表上的哪个项目。这是包含 ListView 的片段的代码:
public class ListViewer extends Fragment {
private ListView list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInsanceState) {
View v = inflater.inflate(R.layout.activity_list_view, container, false);
Player player_data[] = new Player[] {
new Player(R.drawable.bschenn1, "Brayden Schenn", "Age: 21, Drafted 5th overall by LA King in 2009", "Center - #10"),
new Player(R.drawable.giroux, "Claude Giroux", "Age: 25, Drafted 22nd overall by Philadelphia Flyers in 2006", "Center - #28"),
new Player(R.drawable.hartnell, "Scott Hartnell", "Age: 30, Drafted 6th overall by Nashville Predators in 2000", "Left Wing - #19")
};
PlayerAdapter adapter = new PlayerAdapter(getActivity(), R.layout.list_row, player_data);
list = (ListView)v.findViewById(R.id.list);
View header = (View)inflater.inflate(R.layout.listview_header_row, null);
list.addHeaderView(header);
list.setAdapter(adapter);
return v;
}
}
这是适配器的代码:
public class PlayerAdapter extends ArrayAdapter<Player> {
Context context;
int layoutResourceId;
Player data[] = null;
public PlayerAdapter(Context context, int layoutResourceId, Player[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
PlayerHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new PlayerHolder();
holder.imageIcon = (ImageView)row.findViewById(R.id.list_image);
holder.txtplayerName = (TextView)row.findViewById(R.id.title);
holder.txtageDraft = (TextView)row.findViewById(R.id.artist);
holder.txtpositionSNum = (TextView)row.findViewById(R.id.duration);
row.setTag(holder);
} else {
holder = (PlayerHolder)row.getTag();
}
Player player = data[position];
holder.imageIcon.setImageResource(player.image);
holder.txtplayerName.setText(player.playerName);
holder.txtageDraft.setText(player.ageDraft);
holder.txtpositionSNum.setText(player.positionSweaterNum);
return row;
}
static class PlayerHolder {
ImageView imageIcon;
TextView txtplayerName;
TextView txtageDraft;
TextView txtpositionSNum;
}
}
任何帮助深表感谢。