0

In my App I'm using the Android Navigation Component. My MainActivity has a NavigationGraph and I can navigate properly. Since I also need to implemend Search functionality I added a SearchActivity with a SearchFragment. The Search shows a RecyclerView with the Resultset. When I click one of these Results I want to navigate to the specific Fragment of MainActivity.

Unfortunately the App just Navigates to the first Fragment of MainActivity. How do I navigate to a Fragment of another Activity?

NavGraph of MainActivity: NavGraph of MainActivity

NavGraph of SearchActivity: NavGraph of SearchActivity

I navigate to the Fragment of MainActivity by this:

Bundle bundle = new Bundle();

bundle.putInt(SessionFragment.ARG_PARAM1, mSessions.get(position).session.getId());
navController.navigate(R.id.sessionFragment, bundle);

Any ideas?

polyte
  • 449
  • 2
  • 13
  • NavigationComponent recommends using one Activity and multiple fragments. Why do you want to create separate Activity for Search and not a Fragment? – Mariusz Brona Jun 26 '20 at 09:35
  • You would not be having this problem if there weren't multiple Activities in the first place. Now you'd have to add a new Activity just to be able to start this Fragment as its first fragment. – EpicPandaForce Jun 27 '20 at 01:04
  • I use Fragments for the MainActivity and want to stick to the Recommendations by NavigationComponent. But the Docs about Search describe to create a Searchable Activity: https://developer.android.com/guide/topics/search/search-dialog#SearchableActivity This SO Question points out that Search inside of a Fragment is not possible: https://stackoverflow.com/questions/7230893/android-search-with-fragments – polyte Jun 27 '20 at 10:35

1 Answers1

0

I ended up configuring my MainActivity as SearchableActivity and pass the SearchQuery to a SearchFragment.

AndroidManifest:

<activity android:name=".MainActivity">
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>

Then on the MainActivity I check for the SearchIntent and navigate to it with the Query as Argument:

Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
    NavDirections action = HomeFragmentDirections.showSearch(
       intent.getStringExtra(SearchManager.QUERY)
    );
    navController.navigate(action);
}

In my SearchFragment I handle the Search as described by the Google Docs. This may not be the best solution, but works.

polyte
  • 449
  • 2
  • 13