Home Ask Login Register

Developers Planet

Your answer is one click away!

user1721936 February 2016

How to automatically collect analytics events for button click in android?

I have to implement Automatic Event Tracking in android

Need to automatically collect analytics data on all button clicks and page views but it has to be done in a generic way so that I don't need to write the Analytics code again for every click.

Example: I have 2 buttons on my activity each of them having a click listener. Now i want to call Analytics.track(String buttonName) so that i do not have to add this in every click listener. The data that should be passed in tracking is button Name.


meynety February 2016

A way (probably not the ultimate way) to do that could be extending Button (or View), and putting analytics code into the View#performClick() method.

As for the buttonName, it can be a a field of your custom View class, that you can set programmatically or even via an XML custom attribute.

Global implementation :

  • Create a custom XML attribut : create a file named attrs.xml in the ressource folder :

        <declare-styleable name="tracking">
            <attr name="tracking_name" format="string" />
  • Create a custom Button (or View) class, that overwrite performClick() method and call Analytics.track() with the string gotten from your XML custom attribute or set programmatically :

    public class TrackedClickButton extends Button {
        private String mTrackingName;
        public TrackedClickButton(Context context) {
        public TrackedClickButton(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(context, attrs);
        public TrackedClickButton(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init(context, attrs);
        public TrackedClickButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
            init(context, attrs);
        private void init(Context context, AttributeSet attrs) {
            TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.tracking);
            if (array.hasValue(R.styleable.tracking_name)) {
                mTrackingName = array.getString(R.styleable.tracking_name);
        public void setTracking 

Post Status

Asked in February 2016
Viewed 2,306 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life