Skip to content

Instantly share code, notes, and snippets.

@frogermcs
Last active July 25, 2017 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frogermcs/41e9336920b8c778922b83bee2c74898 to your computer and use it in GitHub Desktop.
Save frogermcs/41e9336920b8c778922b83bee2c74898 to your computer and use it in GitHub Desktop.
public class CustomButton extends AppCompatButton {
@Inject
AnalyticsTools analyticsTools;
private String analyticsScreenName;
private String analyticsLabel;
public AzimoButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
//More view constructors here...
private void init(AttributeSet attrs) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.CustomButton, 0, 0);
try {
analyticsLabel = ta.getString(R.styleable.CustomButton_analyticsLabel);
analyticsScreenName = ta.getString(R.styleable.CustomButton_analyticsScreenName);
} finally {
ta.recycle();
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
validateAnalyticsSettings();
}
//Crash early to make sure that you won't miss any button when labeling
private void validateAnalyticsSettings() throws RuntimeException {
if (analyticsLabel == null) {
throw new RuntimeException("Analytics label attribute is required");
}
}
@Override
public boolean performClick() {
logButtonClick();
return super.performClick();
}
private void logButtonClick() {
BaseActivity activity = getActivity();
if (activity != null) {
analyticsScreenName = activity.getScreenNameForAnalytics();
}
analyticsTools.logButtonClick(analyticsScreenName, analyticsLabel);
}
/**
* Unwrap Activity from possible ContextThemeWrapper
*/
private BaseActivity getActivity() {
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof BaseActivity) {
return (BaseActivity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment