我正在尝试编写BaseAdapter代码,我希望在每个onClickListener上获取ViewHolder标记ID,但在每个索引中我都没有获得ViewHolder标记ID,它总是给出第一个ViewHolder标记ID。如果那么将有10个项目,如果我点击第3个项目然后也在Toast消息中我从第一个获得Id。但是在TextView中,id正确显示。
MyCode:
public class MyAdapter extends BaseAdapter{
Activity activity;
Context context;
ArrayList<String> dataList;
public MyAdapter(Activity activity, Context context,ArrayList<String> dataList)
{
this.activity = activity;
this.context = context;
this.dataList = dataList;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return dataList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return dataList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return dataList.size();
}
public class ViewHolder {
TextView data_txt
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
holder = new ViewHolder();
if(convertView==null){
convertView = mInflater.inflate(R.layout.data_layout, parent,false);
holder.data_txt = (TextView) convertView.findViewById(R.id.data);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.data_txt.setText(""+holder);
holder.data_txt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, ""+holder, Toast.LENGTH_SHORT).show();
}
});
return convertView;
} }
所以,我的问题是如何在Toast消息中获取特定的持有者ID。请告诉我,建议我一些好的解决方案。
答案 0 :(得分:0)
将此字段添加到ViewHolder:
public class ViewHolder {
TextView data_txt
int position;
}
更改getView()中的代码:
if(convertView==null){
holder = new ViewHolder();
LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.data_layout, parent,false);
holder.data_txt = (TextView) convertView.findViewById(R.id.data);
holder.position = position;
convertView.setTag(holder);
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int position = ((ViewHolder)(v.getTag)).position;
Toast.makeText(context, Integer.toString(position), Toast.LENGTH_SHORT).show();
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.data_txt.setText(""+ Integer.toString(position));
holder.position = position;