Search code examples
androidandroid-layoutlistviewlistviewitem

Changing ListView item layout from adapter with onClick


I am working with a listview and I have 2 different layouts in raw.xml, and I am trying to control them with their visibility (GONE,VISIBLE) in my custom listview adapter class. I want to change specific item's layout onClick. But when I click on listview items, only last item's layout effects even if I don't click on it.Here is my code.Thanks in advance.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/advertisement_expandable"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        .
        .
        .
    </LinearLayout>

    <RelativeLayout
        android:layout_margin="10dp"
        android:id="@+id/layout2"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        .
        .
        .
        </LinearLayout>
    </RelativeLayout>
</RelativeLayout>

At adapter I am using;

RawView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(currentAdvertisement.isExpanded){
                    layout1.setVisibility(View.VISIBLE);
                    layout2.setVisibility(View.GONE);
                    currentAdvertisement.isExpanded=false;
                }else{
                    layout1.setVisibility(View.GONE);
                    layout2.setVisibility(View.VISIBLE);
                    currentAdvertisement.isExpanded=true;
                }
            }
        });

Solution

  • I think you need something like this

    RawView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    View layout1 = v.findViewById(R.id.layout1);
                    View layout2 = v.findViewById(R.id.layout2);
    
                    if(currentAdvertisement.isExpanded){
                        layout1.setVisibility(View.VISIBLE);
                        layout2.setVisibility(View.GONE);
                        currentAdvertisement.isExpanded=false;
                    }else{
                        layout1.setVisibility(View.GONE);
                        layout2.setVisibility(View.VISIBLE);
                        currentAdvertisement.isExpanded=true;
                    }
                }
            });
    

    Otherwise if you inflated it in your adapter, you override all the times thw two variables and them refer always to the last inflated views