Search code examples
androidandroid-listviewbaseadapterlistviewitem

Android Listview items click


I have a listview with a custom BaseAdapter that fills listview items from json/internet.

In each listview item i have a pseudo buttons(FrameLayouts) with on click event attached to them. When "MAYBE" is clicked for example, I make a call to a server and change event status to "Maybe". After call comes back with success, I would like to change FrameLayouts background to appropriate color (Orange for Maybe).

Where i am having difficulty is to reference other/neighboring FrameLayouts so i can change their backgrounds to "neutral".

enter image description here

All of my events are in BaseAdapter and i set onClick event in GetView method.

My question is: Is there a better way/ how to setup onclick event for each FrameLayout so clicked FrameLayout is aware on click event of other neighboring FrameLayouts so i can change their background to neutral and selected background to respected color.

Thanks.


Solution

  • in your XML add theese attibutes to your FrameLayout(Button)

    android:clickable="true"
    android:onClick="onMaybeClick"
    

    Then in your baseAdapter getView() method you find the FrameLayout by

    FrameLayout maybeBtn = (FrameLayout)convertView.findViewById(R.id.list_item_maybe_btn);
    maybeBtn.setTag(4257 + postion);
    

    You can also set the maybeBtn onClickable in the getView() instead of XML, the same goes for the clicklistener.

    In your activity you can the create a onButtonClick(View v) method

    public void onMaybeClick(View v)
    {
       int position = (Integer)((FrameLayout)v).getTag() - 4257; //To get the position of the click
    
       LinearLayout parent = (LinearLayout)v.getParent();
    
       FrameLayout btnYes = (FrameLayout)parent.getChildAt(0); //first button
       FrameLayout btnNo = (FrameLayout)parent.getChildAt(2); //second button
    
       ServerCallback(new requestListener(){
           ifSuccess(){
               v.setBackground(...);
           }
       ]);
    }