Search code examples
androidincludeonclickonitemclicklistener

android common OnItemClickListener and separate button listeners


In my app I have around 12 activities. The first layout of my activity is a list view. By clicking each list it gets redirected to other activities. I have implemented the Listview with OnItemClickListener and is working good.

In all the other 11 activities, I have a common title bar with a logo and a button named as S. When the user clicks on the S button, I am showing the same list of items in the First activity of my app, within the current activities by splitting the page. Now instead of writing a separate OnItemClickListener for each activity, how to write it once and use in multiple activities?

In the same way I have placed 3 button in include layout and I am using this in various activities, how to write a separate common button action, it can be used in multiple activities.


Solution

  • While @SamirMangroliya's method works, this is an alternate method you can use, and the one I've been using for a while.

    Create your listener in another class file (say, MyClickListener.java):

    public class MyClickListener implements OnItemClickListener {
        // This can be OnClickListener, OnTouchListener, whatever you like.
        // Implement your method here:
        public onItemClick(...) {
            // Your selection process, etc.
        }
    }
    

    Then in each of your Activity objects, all you have to do is:

    myObject.setOnItemClickListener(new MyClickListener());