Search code examples
androidandroid-listviewandroid-viewgroup

Clicklistener for View Group Android


I am working on android application in which i am using ViewGroup to show my footer in my list view. Now i want to make an listener event for that view group, so user can press that footer. My code to make that footer and view group is given below along with the xml.

ViewGroup footer = (ViewGroup) getLayoutInflater().inflate(R.layout.footer_view, mListView, false);
                    View header = getLayoutInflater().inflate(R.layout.footer_view, null);
                    Button headerButton = (Button)header.findViewById(R.id.footerRefreshBtn);
                    mListView.addFooterView(footer);

                    headerButton.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             Toast.makeText(context, "I am clicked", Toast.LENGTH_LONG).show();
                         }
                    });
// It is not showing toast message on click.

XML for footer:

<?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:clickable="true"
    android:orientation="vertical" >

<Button
    android:id="@+id/footerRefreshBtn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:layout_gravity="center_horizontal"
    android:text="Refresh Button"
    android:textColor="@color/white"
    android:background="@color/gray" />

</LinearLayout>

Solution

  • I couldn't find out how to setOnClickListener to a footer, but I found a different solution. I think you could use this, just find the footerRefreshBtn and set Button's OnClickListener only before or after you add footer view. Both ways are working.

        LayoutInflater inflater = getLayoutInflater();
        ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, mListView, false);
    
        mListView.addFooterView(footer, null, false);
    
        mListView.setAdapter(mAdapter);
    
        Button footerRefreshBtn = (Button) footer.findViewById(R.id.footerRefreshBtn);
    
        footerRefreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "I am clicked", Toast.LENGTH_LONG).show();
            }
        });
    

    This way, you are only assigning the Button's onClick event.

    Nevertheless if you still want to set an onClickListener to a whole footer, you can get footer's layout and set an onClickListener to this layout using the method I mentioned above.