As I'm creating a library and I wanted to track the button clicks from the application using that library(kind of analytics clicks tracking library). So I have tried so many things and those didn't work for me. I have gone through the below link and I came to know that we can add multiple listeners using the composite pattern.
Attaching multiple listeners to views in android?
Please help me here to achieve my requirement.
Here is the code, which I have tried
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameFragment, new FragmentA());
fragmentTransaction.commit();
Button button = findViewById(R.id.buttonDemo);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("test", "Button Click 1");
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("test", "Button Click 2");
/*Field field = null;
try {
Log.e("test", "CLASS NAME: "+v.getClass().getName());
field = Class.forName(v.getClass().getName()).getDeclaredField("mOnClickListener");
View.OnClickListener retrievedListener = (View.OnClickListener) field.get(v);
Log.e("test", ""+retrievedListener.toString());
} catch (NoSuchFieldException e) {
e.printStackTrace();
Log.e("test", "Exception: NoSuchFieldException");
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.e("test", "Exception: ClassNotFoundException");
} catch (IllegalAccessException e) {
e.printStackTrace();
Log.e("test", "Exception: IllegalAccessException");
}*/
ClickListener listenerCollector = new ClickListener();
listenerCollector.addOnclickListener(this);
}
});
}
}
another class
public class ClickListener implements View.OnClickListener {
private ArrayList<View.OnClickListener> clickListeners = new ArrayList<>();
public void addOnclickListener(View.OnClickListener listener){
clickListeners.add(listener);
}
@Override
public void onClick(View v) {
for(View.OnClickListener l : clickListeners){
l.onClick(v);
Log.e("test", "onclick from composite click");
}
}
}