Reputation: 793
I have a general question about the creation of multiple similar activities. Suppose we have an app in which you could order several different dishes (let's say we have 20 dishes). For every dish there is an activity for customizing (with regard to the size) and ordering it. So basically all the activities are quite similar. My question now is, do I have to create a separate activity for all the 20 dishes or is there a more elegant way of doing this by only creating one activity and passing the individual values of the dishes to it?
I know that there are abstract classes in Java. But even if I use them I will still have to create an activity for every dish and a separate XML file for the layout, right?
Upvotes: 1
Views: 155
Reputation: 1345
You do not need to create a seperate activity for each dish! All you need is to do is use a getIntent() method to know where the the click is coming from and populate your view with the corresponding values.
Lets say you want to Order dish 1, on the button to order the dish, attach the intent to open the activity and attach the extras, do this for the other dishes. On the activity to display the dish info, obtain the extras and use them to populate the views for the XML. This means you can reuse an activity for many dishes.
Edit: Forgot to add code snippets. Assume that you are in the activity where you get to choose the dish.
In this case I am assuming the user wants tacos, I package the name of the dish in an extra and send to the DishInfo activity as seen below.
Intent intent = new Intent(this, DishInfo.class);
String dish = "Tacos";
intent.putExtra("DISH_NAME", dish);
startActivity(intent);
In the DishInfo activity, I get the intent that opened the activity by calling the getIntent() method and get the String with the getStringExtra() in this case because what I passed was a string. I set the text I got from the Intent to the textview.
TextView dishDisplayed = findViewById(R.id.TextView);
Intent intent = getIntent();
String dish = intent.getStringExtra("DISH_NAME");
dishDisplayed.setText(dish);
I made this example assuming that the important info you want to send to the new Activity is the simple name of the dish. I also assumed you would use the traditional findViewById() rather than bindings.
Intents are more powerful than this, you can read more about them here https://developer.android.com/guide/components/intents-filters
Upvotes: 1