If all buttons have similar functionality, which differs only in a parameter that can be identified, it is better to create one listener and assign it to all buttons.
The location of the listener depends on the amount of variables that it needs to use. If he needs to use some method variables, he must be created inside the method, if he uses members of the class, he must be created inside the class.
For example, if you have ten buttons, each of which should start a different action, you can create a map of views and actions, and the corresponding action will begin in the listener's foundation:
Map<View, Class<?>> viewActivityMap = new HashMap<View, Class<?>>(); // fill it somewhere // in onCreate View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { Class<?> classToStart = viewActivityMap.get(v); Intent intent = new Intent(YourActivity.this, classToStart); startActivity(intent); } } button1.setOnClickListener(listener); button2.setOnClickListener(listener); button3.setOnClickListener(listener);
In the case of listeners, the only real reason that I see the creation of an inner class is to create a constructor that receives parameters different from the implemented class / interface constructors.
MByD
source share