-1

I am relatively new to Android development however I am very familiar with java.

I would like to create an app that displays the periodic table of elements which will have buttons for each element and when a button will be touched, the details of that elements would be shown.

I don't want to create a separate activities for each button. I want to create just one activity and when a button will be touched it's details will be shown. If I go on creating separate activities for each button, I will have to create 100+ activities, which I don't want.

How can I create just one activity and when a element's button is pressed, it's unique details is shown?

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • 1
    Create a detail activity . When a button in MainActivity is pressed , then pass details of element using Intent and display it in details activity . – Rishabh Maurya May 25 '17 at 15:39
  • Possible duplicate of [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – Rishabh Maurya May 25 '17 at 15:41

2 Answers2

0

You absolutely don't have to create a separate activity for every element.

Once you have the list of elements you can pass the element from the mainActivity to the detailsActivity and, using an adapter, inflate the detail activity with the selected element.

The steps are the following:

  1. Create a Model class of your Element:

    public Class Element {
        // params
        // constructor
        // getters and setters
        // implement parcelable
    }
    
  2. Create a List of elements:

    List<Element> list = new List<>();
    
    list.add(new Element(/* pass your params */));
    ...
    
  3. Giving that you already have a Main_Activity where you have your element grid, create a second detailsActivity():

    public class detailsActivity extends AppCompatActivity {
        @Override protected void onCreate(Bundle b) {}
    }
    
  4. Pass your element from MainActivity to detailsActivity when you click on the grid using Intent and Bundle:

    Intent details = new Intent();
    Bundle b = new Bundle();
    b.putParcelable("selected", element);
    details.putExtras(b);
    startActivity(details);
    
  5. Create an adapter to inflate your detailsActivity with the selected Element.

Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49
Daniele
  • 4,163
  • 7
  • 44
  • 95
0

For this you can simply achieve this by fragments. In one fragment let's say fragment1 you keep the buttons and in the other fragment let's say fragment2 you keep the details. Whenever you press the button in fragment1 send the details by Bundle to fragment2 and update the details in fragment2.

By this you will used just one activity and two fragments.

Take this tutorial, this will help you to understand Fragments. http://www.vogella.com/tutorials/AndroidFragments/article.html

Sho_arg
  • 383
  • 3
  • 13