I have a ListView, with items with this layout:
<LinearLayout ...>
<LinearLayout ...>
<!--Elements -->
</LinearLayout>
<LinearLayout ...>
<!--Elements -->
</LinearLayout>
</LinearLayout>
So my items have two different sections. I want to be able to setup different onclickListener inside each item(one for each LinearLayout). I have tried so far to override the onListItemClick, but it doesnt seem to work properly:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ViewGroup vg = (ViewGroup)v;
vg.getChildAt(0).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mCtx, "element1", Toast.LENGTH_SHORT).show();
}
});
vg.getChildAt(1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mCtx, "element2", Toast.LENGTH_SHORT).show();
}
});
}
Any ideas how to tackle the problem?
Thanks.
You have to use set onclicklistener
to all elements inside ListView.
I have created a listview. set an adapter to the listview. My adapter is reponsible to show each element of the listview. so inside getView()
I will assign onclicklistener to all the elemnts to whom i want to get the click event.
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.item, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+position);
holder.image.setTag(data.get(position));
holder.image.setOnClickListener(this);
holder.text.setOnClickListener(this);
imageLoader.DisplayImage(data.get(position), activity, holder.image);
return vi;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
System.out.println("...clicked view is...."+arg0);
}
Thanks Deepak
You dont need a OnClickListener for each list item, but you do need to find each listview, e.g. in your activity OnCreate
listView1 = (ListView) this.findViewById(R.id.ListView1);
listView2 = (ListView) this.findViewById(R.id.ListView2);
then your onListItemClick becomes -
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (l.equals(listView1))
{
switch (position)
{
case 0:
Toast.makeText(mCtx, "list1-element1", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(mCtx, "list1-element2", Toast.LENGTH_SHORT).show();
break;
}
}
else
{
switch (position)
{
case 0:
Toast.makeText(mCtx, "list2-element1", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(mCtx, "list2-element2", Toast.LENGTH_SHORT).show();
break;
}
}
}
Unless I've misunderstood what your trying to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With