Search code examples
androidonitemclicklistenerandroid-event

Is there a cleaner approach to click listeners in Android?


So I have been developing in Android for quite some time and I am natively a .Net developer. The problem I am facing is that my code looks awful, and I really dislike the way that Java\Android not sure which, makes click events appear in code. In this example below I have a List View with a click event.

list_view.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // TODO Auto-generated method stub

        }
    });

In .Net I would have set my click event in my Initialize Components method and then implemented it in my main code page. How do I tell android to use a click event method below in my code instead of referencing it right there. Maybe something like this?

list_view.setOnItemClickListener(onItemClick());

Later on in my code page.

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }
});

All in all I am just looking for a cleaner approach to wiring my events up to my controls so I can read the code better. It is a struggle moving to Java and Android when originally being a .Net developer.

Thanks!

Edit

Thank you for the answer below I posted my work here.

list_view.setOnItemClickListener(list_view_onItemClickListener);


//below in my code
private OnItemClickListener  list_view_onItemClickListener = new OnItemClickListener (){
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }

};

Solution

  • you can try this!