问题描述
- ListView 获得点击 view 和相应的 row
-
我想从 listview 子类的 onClick 事件中获取点击的 row。我能获取点击 item 但是不能在那个事件中点击 row。如何解决这个问题。
代码如下:public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); Holder holder = new Holder(); pos = position; if(convertView == null) { System.out.println(position); convertView= inflater.inflate(R.layout.list_layout,(ViewGroup)parent.findViewById(R.layout.list_layout)); holder.form_name = (TextView) convertView.findViewById(R.id.list_text); holder.form_details = (TextView) convertView.findViewById(R.id.button_text); holder.form_details.setOnClickListener(new OnClickListener(){ public void onClick(View v) { // TODO Auto-generated method stub System.out.println(pos); //Here i am able to get clicked view but pos has always // last value System.out.println("button view clicked for "+cipt_list.get(pos).cipt); }}); System.out.println(holder.form_name); convertView.setTag(holder); } else{ holder = (Holder) convertView.getTag(); } ciptDetails cipt = cipt_list.get(position); holder.form_name.setText(cipt.cipt); return convertView; }
解决方案
在点击监听器前设置:
holder.form_details.setId(position);
在 onClick 方法中使用 v.getId()
就会给出位置。
解决方案二:
一种方法,使用 OnItemClickListener
list.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
}
};
第二种,在 getView() 方法中获得位置,改成 "final int position",然后在 view's onClickListener() 中访问
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Holder holder = new Holder();
pos = position;
if(convertView == null)
{
System.out.println(position);
convertView= inflater.inflate(R.layout.list_layout,(ViewGroup)parent.findViewById(R.layout.list_layout));
holder.form_name = (TextView) convertView.findViewById(R.id.list_text);
holder.form_details = (TextView) convertView.findViewById(R.id.button_text);
holder.form_details.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// you can access the position here
System.out.println(pos);
//Here i am able to get clicked view but pos has always
// last value
System.out.println("button view clicked for "+cipt_list.get(pos).cipt);
}});
System.out.println(holder.form_name);
convertView.setTag(holder);
}
else{
holder = (Holder) convertView.getTag();
}
ciptDetails cipt = cipt_list.get(position);
holder.form_name.setText(cipt.cipt);
return convertView;
}
时间: 2025-01-30 10:40:27