Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple clickable views inside listview item

I am trying to create an item in a ListView that has multiple options; view and edit. I would like to create it in exactly the same way as android's contact system - see below:

enter image description here

I have added the red boxes to illustrate the behaviour I want. If you press within the left red-box, you call the contact. If you press within the right red-box, you send a text message to the contact. I have already created a similar layout in XML, but I am having trouble implementing this functionality in code.

I have tried to create custom android:onClick function calls for the separate layouts within the item, but calling an onClick method only allows you to pass in the View as a parameter, but not the position. Needing the position to use listview.getItemAtPosition function, I tried to use listview.getPositionForView to return the position but found this was extremely unstable and was very easy to return incorrect positioning due to recycling of views.

I then tried to set the item's position as the 'tag' in the getView method of my adapter, like so: convertView.setTag(position). But on the onClick method of my activity, I try and use getTag and cast it back to an integer, and it always returns null, which I find puzzling.

What is the best way of implementing a list populated by items with multiple buttons/layouts on each item?

like image 882
Mike Baxter Avatar asked Jul 31 '26 05:07

Mike Baxter


1 Answers

You can create an onClick event on each views in your row like this :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/text_id"
        android:layout_width="0sp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:onClick="textOnClickEvent"/>


    <ImageButton
        android:id="@+id/button_id"
        android:layout_width="@dimen/width_button"
        android:layout_height="match_parent"
        android:onClick="imageOnClickEvent"
        android:src="@android:drawable/ic_menu_delete" />
</LinearLayout>

Or even, add onClick listeners on each views in the getView method...

more info on this here.

like image 188
Guian Avatar answered Aug 01 '26 18:08

Guian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!