I was developing and I thought of a little problem I'm encountering on Android development with Java. I have this MainActivity class. The view are just some buttons, and every button calls a different activity. Right now I have this code
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.pedidos);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PedidosActivity.class);
startActivity(intent);
}
});
}
So, considering that I need to add two more buttons so I can start two more different activities depending on which button do I press, I would need two repeat this code n times for every new Activity that I add in the project. I believe that there must be a better way to do this. I already thought I could do a factory pattern, using a class as Interface with a method that would be callActivity() Like this:
public interface ActivityFactory(){
public OnClickListener setOnClickListener();
}
This method would recieve through parameters the context of the activity which is instantiating the new view, an Enum type with the different views as parameters, and it would return a new eventListener for the button that would get you to the new view, like this:
@Override
button.setOnClickListener(getContextActivity(), EnumClass.NewActivity);
I haven't found any kind of post/blog/thread about this subject, maybe because I'm still newbie with Android development, but I find this very interesting and valuable to know for any Android developer, so any kind of approach is truly appreciated.
EDIT: I think that I left part of the explanation, so I will add it here. I wanted to skip the instantiation of the new two buttons, so I wanted to know the way of only instantiate one button and give it the value of the view depending on which button you press.