Android Studio Single activity acting as many

I have looked everywhere but don't seem to be able to find what I am looking for. I have an activity with multiple buttons, each button opens a new activity with an identical recyclerview layout, but different data. I am wondering if it is possible to use one activity and layout instead of multiple? this way instead of having 10+ activities (one for each button) I only have to manage one when a button is clicked and simply pass the necessary list data to it.

I believe you could set the intents for each button to call the same activity but with an integer such as 1-10, in the activity it takes the value and decides which list should be presented? If anyone thinks of how this could be done or a simpler way I would greatly appreciate it!

2 answers

  • answered 2018-07-11 03:31 Rajan Prasad

    Yes, there are various ways to do that.

    1. You could use multiple fragments on the same activity. Then add/remove fragments on each button click.
    2. You can have multiple layouts within your activity. Say you have two buttons, and you have three layouts layout1, layout2, layout3, sequentially one after the another. So if initially, layout1 is visible and the rest are gone using layout.setVisiblity(View.GONE), if you click button1, ypu can do layout1.setVisiblity(View.GONE); layout3.setVisiblity(View.GONE); layout2.setVisiblity(View.VISIBLE) and vice-versa for pressing button2.

  • answered 2018-07-11 06:16 Amenediel

    Are all the activities opened by the buttons similar? If so, you could only take care of the changes in the elements of the layout & specify conditions.

    For instance, if you click a button, instead of changing the whole thing, you only go into the buttons & change their texts with btn.setText("..."). You could define different conditional statements inside the onClickListener of that button. It could be something like:

    if(btn.getText().equals("a certain text that you set to the button")){
        doSomething();
    else if(btn.getText().equals("another option")){
        doSomethingElse();
    

    Following this logic, you could continually update the elements in your layout & your code will decide what to do depending on what's stored in these elements.

    The second option that comes to my mind would be creating different xml layout files & simply changing the layout of your MainActivity to the appropriate one depending on what stage of your process you are at.

    I hope this helps,