'Android Programming - Navigation Drawer Multiple Instances of Same Fragment
I am trying to make a weather app where each location that the user adds, it will be shown in the Navigation Drawer.
I would like to have multiple items in the Navigation Drawer, each item a different location and when a location is being clicked, a fragment will load the weather info for it. I want the same fragment as the layout for any location will be the same.
The info will be loaded via an API call based on the location that was clicked.
My question is, how can I have the same fragment multiple times in the navigation drawer if this is possible?
I thought about creating a new fragment for each location when loaded from the DB but this might be overwhelming with lots of locations.
Thanks in advance.
Solution 1:[1]
you could actually use same fragment and assign different constructors to the fragment object when you're going to respond to user click ...
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Log.e("NAVIGATION------", item.toString());
switch(){
if(item == R.id.nav_scenario_1){
SettingsFragment fragment = new
SettingsFragment();
Bundle arguments = new Bundle();
arguments.putString( string_key , desired_string);
fragment.setArguments(arguments);
final FragmentTransaction ft =
getFragmentManager().beginTransaction();
ft.replace(R.id.content, fragment , FRAGMENT_TAG);
ft.commit();
}
....
}
return true;
}
});
or from the navigation controller you could use something like that in order to pass the data ...
<fragment
android:id="@+id/nav_terms"
android:name="com.google.fragment.MainFragment"
android:label="@string/menu_terms"
tools:layout="@layout/fragment_main" >
<argument
android:name="UsedObjectString"
app:argType="string"
android:defaultValue="some_data_as_json"/>
</fragment>
and then could retrieve it in the fragment like that :
if(getArguments() != null) {
String stringObject =
MainFragmentArgs.fromBundle(getArguments()).UsedObjectString();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Waged |