Search code examples
androidandroid-fragmentsandroid-intentandroid-activityandroid-viewpager

How to launch a fragment within a ViewPager from an Activity


Apologies in advance, if there is a similar question to this that has already been answered. However, I have tried all possible solutions and have failed.

Right so I am creating an app , which contains three fragments within a ViewPager, which is set in the main Activity. Meaning that when I execute the android application, it will display the first fragment, and swiping left will display the other fragments.

The problem is, in my Fragment I have a ListView and also a FloatingActionButton. When the user wants to enter a new entry, they press the button and a new activity launches where they input the data into an EditText. (To this point it works)

How do I now relaunch that fragment so that it returns to the fragment and shows the updated ListView?

In essence, what is an alternative way of using.

Intent i = new Intent(MainActivity.this,AnotherActivity.class);
startActivity(i);

As that is what I use when dealing with activities.


Solution

  • In order to launch a fragment, you must first launch an activity which contains the fragment. There are at least three different ways to return to the ViewPager activity.

    1. Use an intent to launch a new instance of the activity. It sounds like you know how to do this.

    2. Provide Up Navigation to allow your user to go back to the original activity with the ViewPager. If your ListView is implemented correctly, it will load the data, including the new record.

    3. Use startActivityForResult() instead of startActivity() to launch the "editing activity". This is handy if you allow the user to edit only a single record.