Search code examples
androidandroid-layoutcardlayoutcardslib

how to add onClickListener to buttons inside CardLayout


I am using Gabrielemariotti's Cardslib library to implement card layout in my android application. I am using a custom layout for my cards. Below is the code for creating custom cards:

Card card = new Card(getActivity().getApplicationContext(), R.layout.status_card);
card.setTitle("sample title");

I have three buttons at the bottom of my card (like buttons in Facebook android app). I want to set onClickListener for these buttons. But I am not sure how to do that.

Please help me here.

Thanks,


Solution

  • You have to define your layout. Then create a Card with this layout, and override the setupInnerViewElements method. Inside this method you can define your OnClickListener on your buttons, and you can access to all card's values.

     public class CustomCard extends Card {
    
            /**
             * Constructor with a custom inner layout
             *
             * @param context
             */
            public CustomCard(Context context) {
                super(context, R.layout.carddemo_mycard_inner_content);
            }
    
    
            @Override
            public void setupInnerViewElements(ViewGroup parent, View view) {
    
                //Retrieve button 
                Button myButton = (Button) view.findViewById(R.id.myButton);
                if (myButton != null) {
                    myButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(getContext(), "Click Listener card=" + getId(), 
                                  Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }