Map fragment in a bottom navigation bar - Android Studio - java

I new on programming android apps. I want to display a map in one of the fragments that I created for a bottom navigation bar. However, I'm not sure what I should include in the the MainActivity.java, the fragment_map.xml, and the MapFragment.java.
I share my code to see if anyone could please help me to figure it out what I should include in each one.
Thanks :)
MapFragment.java
public class MapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the layout file as the content view.
setContentView(R.layout.activity_main);
// Get a handle to the fragment and register the callback.
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private void getMapAsync(MapFragment mapFragment) {
}
private void setContentView(int activity_main) {
}
// Get a handle to the GoogleMap object and display marker.
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker"));
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private Fragment mapFragment = new MapFragment();
private Fragment storyFragment = new StoryFragment();
private Fragment infoFragment = new InfoFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.body_container, mapFragment, null).commit();
fragmentManager.beginTransaction().add(R.id.body_container, storyFragment, null).commit();
fragmentManager.beginTransaction().add(R.id.body_container, infoFragment, null).commit();
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//bottomNavigationView.setSelectedItemId(R.id.mapsFragment);
bottomNavigationView.setOnItemSelectedListener(navListener);
}
private NavigationBarView.OnItemSelectedListener navListener = new NavigationBarView.OnItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_map:
fragmentManager.beginTransaction().replace(R.id.body_container, mapFragment).commit();
break;
case R.id.nav_story:
fragmentManager.beginTransaction().replace(R.id.body_container, storyFragment).commit();
break;
case R.id.nav_info:
fragmentManager.beginTransaction().replace(R.id.body_container, infoFragment).commit();
break;
}
return true;
}
};
}
fragment_map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>

Related

Multiple fragments saveInstance using bottom nav android problem

My app has bottom navigation view .Using bottom navigation I'm switching the fragments .I want to save the instance of every fragment .but I'm unable to do that because my code is missing something.Please help me to solve that issue. My code:
public class MainActivity extends AppCompatActivity {
private MyFragment fragment;
private YourFragment yourFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView=findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnItemSelectedListener(item -> {
switch (item.getItemId()){
case R.id.frag_one:
if (savedInstanceState == null) {fragment = new MyFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment, "myFragmentName")
.commit();
} else {
fragment = (MyFragment) getSupportFragmentManager()
.findFragmentByTag("myFragmentName");
}
break;
case R.id.frag_two:
if (savedInstanceState == null) {yourFragment = new YourFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container,yourFragment,"myFragmentName")
.commit();
} else {
yourFragment = (YourFragment) getSupportFragmentManager()
.findFragmentByTag("myFragmentName");
}
break;
}
return true;
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "myFragmentName", fragment);
getSupportFragmentManager().putFragment(outState,"YourFragmentName",yourFragment);
}
}

Activity to Fragment with existing content

I wrote a simple App with Two Activities, The First is my MainActivity and the Second is my MapsActivity.
The Code works perfectly in my MainActivity, when i press a Button i will get redirected to my MapsActivity with fixed LatLng and my actual Location.
Now i came to the conclusion that i want to implent a TabLayout (in Total 3 Tabs).
The First Tab should contain the Buttons and the functionality of my MainActivity
As already all Buttons and all the code is in my MainActivity i need to transfer it to the First Fragment.
This didnt work out, since im using alot of findViewById and the Fragment does not like that.
MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button;
private Button btnred;
private Button btnaura;
private double v1;
private double v12;
private double vend;
private double v1end;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setLogo(R.drawable.fvroth);
button = findViewById(R.id.btnroth);
btnred= findViewById(R.id.btnRednitz);
btnaura = findViewById(R.id.btnaurach);
btnaura.setOnClickListener(this);
button.setOnClickListener(this);
btnred.setOnClickListener(this);
ViewPager2 viewPager2 = findViewById(R.id.viewPager);
viewPager2.setAdapter(new weiherPageAdapter(this));
TabLayout tabLayout =findViewById(R.id.tabLayout);
TabLayoutMediator tabLayoutMediator= new TabLayoutMediator(
tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0: {
tab.setText("Fliesgewässer");
tab.setIcon(R.drawable.ic_baseline_check_24);
break;
}
case 1: {
tab.setText("Weiher");
tab.setIcon(R.drawable.ic_baseline_account_circle_24);
break;
}
case 2: {
tab.setText("Schon-maß und Zeiten");
tab.setIcon(R.drawable.ic_baseline_announcement_24);
break;
}
}
}
}
);
tabLayoutMediator.attach();
}
public void openMapsActivity(){
Intent intent=new Intent(this,MapsActivity.class);
LatLng position= new LatLng(v1,v12);
intent.putExtra("Pos",position);
LatLng positionende = new LatLng(vend, v1end);
intent.putExtra("PosEnde",positionende);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnroth:
v1= 49.21344;
v12= 11.171002;
vend= 49.211946;
v1end= 11.158726;
openMapsActivity();
break;
case R.id.btnRednitz:
v1= 49.250451;
v12= 11.084395;
vend= 49.269385;
v1end= 11.076057;
openMapsActivity();
break;
case R.id.btnaurach:
v1= 49.244672;
v12= 11.043886;
vend=49.254027;
v1end= 11.080881;
openMapsActivity();
break;
}
}
MapActivity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
Location currentLocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
// Construct a GeoDataClient
}
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
currentLocation = location;
Toast.makeText(getApplicationContext(),currentLocation.getLatitude()+""+currentLocation.getLongitude(),Toast.LENGTH_SHORT).show();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng position = getIntent().getExtras().getParcelable("Pos");
LatLng positionende= getIntent().getExtras().getParcelable("PosEnde");
LatLng aktpos = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(position).title("Anfang"));
mMap.addMarker(new MarkerOptions().position(positionende).title("Ende"));
mMap.addMarker(new MarkerOptions().position(aktpos).title("ich").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position,15),1000,null);
}
}
For Better understanding here a Picture of the App.

How to use Helpshift Embeddable Support Fragments Android

I am building an Android app that uses the Helpshift API. It was all working, but I am currently trying to move everything into a TabLayout, using Fragments and an ActionBar. I made a mini app to figure out functionality of the fragments without messing everything else up. I have a home screen where you click a button and it starts the activity containing the TabLayout with the Fragments. I cannot figure out how to make the embeddable support fragments show up in the TabLayout. I'm pretty new to Android, so sorry if my code is not the best. Right now the placeholder is not being replaced in the fragment transaction, and I can't figure out why. I would greatly appreciate any advice! Thank you :) Let me know if I can provide anything else
Here is my main activity class (Helpshift info has been redacted for privacy reasons, hopefully my issue can still be fixed)
public class MainActivity extends AppCompatActivity {
Context mContext;
public ConstraintLayout layout;
Activity goToFragment;
public Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
mContext = getApplicationContext();
goToFragment = MainActivity.this;
start = (Button) findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view) {
launchFragments();
}
});
//HELPSHIFT SET UP
Core.init(All.getInstance());
InstallConfig installConfig = new InstallConfig.Builder()
.setScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
.setEnableInAppNotification(true)
.build();
try {
Core.install(getApplication(),
"****APIKEY*****",
"****DOMAIN*****",
"****APPID******", installConfig);
} catch (InstallException e) {
android.util.Log.e("Helpshift", "install call : ", e);
}
}
private void launchFragments() {
Intent intent1 = new Intent(mContext, HomeTab.class);
intent1.putExtra("fragmentNumber", 0);
startActivity(intent1);
}
}
Here is my ViewPager Adapter class:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager){
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Here is my fragment activity class:
public class HomeTab extends AppCompatActivity {
// ImageButton FindCareButton;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
public Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
Intent intent1 = getIntent();
int var = intent1.getIntExtra("fragmentNumber", 0);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
viewPager.setCurrentItem(var);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
if (findViewById(R.id.placeholder) != null) {
if (savedInstanceState != null) {
return;
}
Fragment faqFragment = new Fragment();
faqFragment = Support.getFAQsFragment(HomeTab.this);
getSupportFragmentManager().beginTransaction().add(R.id.placeholder, faqFragment).commit();
}
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FAQTab(), "FAQ");
viewPager.setAdapter(adapter);
}
}
Here is my FAQTab class:
public class FAQTab extends Fragment {
public FAQTab(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.faq_tab, container, false);
}
}
For layouts, my faq_tab layout is an empty FrameLayout with id "placeholder"
My home_screen layout is a ConstraintLayout with a button (id "button")
And here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sasha.fragment_tester.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/BarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</android.support.design.widget.CoordinatorLayout>

How To Use Maps in Fragment

i want to make maps in android fragment with use extend fragment
this is my code : Maps do not come up, and system force close
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.gmaps, container, false);
SupportMapFragment mapFragment = ((SupportMapFragment) getActivity().getSupportFragmentManager() .findFragmentById(R.id.map));
mapFragment.getMapAsync((OnMapReadyCallback) this.getActivity());
btnFindPath = (Button) view.findViewById(R.id.btnFindPath);
etOrigin = (EditText) view.findViewById(R.id.etOrigin);
etDestination = (EditText) view.findViewById(R.id.etDestination);
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
return view;
please help me, and thank you
You can try the below code :
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i("onActivityCreated", "onActivityCreated");
if(supportMapFragment==null){
supportMapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
loadMapAtPosition(googleMap, CAMERA_INITIAL_LATITUDE, CAMERA_INITIAL_LONGITUDE);
}
});
}
.....
private void loadMapAtPosition(GoogleMap googleMap, double latitude, double longitude){ googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 6.0f)); }
Just Simple if you want to use Map in Fragment.
Try this
in you Fragment class.
GoogleMap map = ((SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
and in your xml.
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
if you use google map within fragment then you should be use map
object like this.you have to use getChildFragmentManager() to find
fragment
<fragment
android:id="#+id/main_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" >
</fragment>
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.main_map);

Android: Navigation-Drawer on all activities

I want to add navigation drawer on all actvities of my Android project. This is the code of the MainActivity:
public class MainActivity extends Activity {
private String[] drawerListViewItems;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
// App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//drawerLayout = (DrawerLayout) findViewById(R.drawable.ic_drawer_2);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
// Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
// just styling option add shadow the right edge of the drawer
drawerLayout.setDrawerShadow(R.drawable.ic_drawer, GravityCompat.START);
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
displayView(position);
drawerLayout.closeDrawer(drawerListView);
}
private void displayView(int position)
{
switch (position)
{
case 0:
secondactivity();
break;
case 1:
Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(MainActivity.this, "3", Toast.LENGTH_LONG).show();
default:
break;
}
}
}
public void secondactivity (){
Intent cambioActivity;
cambioActivity = new Intent (this, SecondActivity.class);
startActivity(cambioActivity);
}
}
In this code I create the navigation drawer, I want the navigation drawer on all activities, so my Second Activity's code is this:
public class SecondActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondactivity);
}
The navigation drawer is on the first activity but there isn't on other activities, why? Can someone help me?
The easy way is that you should create fragments. If you are ready to for little hard thing then this is for you. It will let you have same navigation drawer in all activities.
Create drawer_n_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/drawer_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<YourDrawer
android:id="#+id/drawer_drawer"
android:layout_width="match_parent"
android:layout_height="fill_parent" >
</YourDrawer>
</RelativeLayout>
Your DrawerActivity.class
public class DrawerActivity extends Activity {
public RelativeLayout fullLayout;
public FrameLayout frameLayout;
#Override
public void setContentView(int layoutResID) {
fullLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.drawer_n_activity, null);
frameLayout = (FrameLayout) fullLayout.findViewById(R.id.drawer_frame);
getLayoutInflater().inflate(layoutResID, frameLayout, true);
super.setContentView(fullLayout);
//Your drawer content...
}
}
Now, to include same Navigation Drawer in all your activities and mind one more thing, all your activities must extend DrawerActivity
public class MainActivity extends DrawerActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //layout for 1st activity
}
}
public class SecondActivity extends DrawerActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity); //layout for 2nd activity
}
}
Okay Guys will share my way I do it (in case you are developing project after somebody and there is already tons of activities).
Finally I inflate navigation drawer with one line of code (in onCreate):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this; //context
//setContentView(R.layout.activity_favorites); // Was so
Utils.inflatedNavigationDrawerView(mContext, R.layout.activity_favorites); // Now is
//...
}
next what is Utils? :
public class Utils{
public static void inflatedNavigationDrawerView(Context context, int layoutId){
// Here get view of clear DrawerLayout
final View drawerLayout = View.inflate(context,R.layout.navigation_drawer_inflator, null);
// Next inflate to it passed layout for activity
final View mainLayout = View.inflate(context,layoutId, (ViewGroup) drawerLayout);
// And finally inflate to it fragment for NavigationDraver
final View fragmentLayout = View.inflate(context,R.layout.navigation_drawer_inflator_fragment, (ViewGroup) drawerLayout);
// Next we should try to get our drawer (should check with casting to each activity you want to insert to)
NavigationDrawerFragment drawerFragment = null;
// this block should be repeated for each activity you want to use in.
if (context instanceof FavoritesActivity){
// Set our pack of inflates to contentview
((FavoritesActivity) context).setContentView(mainLayout);
// And now we get NavigationDrawerFragment
drawerFragment = (NavigationDrawerFragment)
((FavoritesActivity) context).getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_fragment);
}
if(drawerFragment != null){ // if null then we missed some castings for activity used in.
// Finally setup our drawer
drawerFragment.setUpEasy(R.id.navigation_drawer_fragment, (DrawerLayout)drawerLayout.findViewById(R.id.drawer_layout), (Toolbar) mainLayout.findViewById(R.id.app_bar));
}
}
}
If you would like to avoid creation of hamburger in Toolbar then you shoud in setUpEasy place: mDrawerToggle.setDrawerIndicatorEnabled(false);
Here is my sample of setup:
public void setUpEasy(int fragmentId, DrawerLayout drawerLayout, Toolbar toolBar) {
mContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolBar, R.string.open, R.string.close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if(!mUserLearnedDrawer){
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), Constants.PREFERENCES_LEARNDRAWER_KEY, mUserLearnedDrawer+"");
}
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerToggle.setDrawerIndicatorEnabled(false); // If false then no hamburger menu.
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
and views used:
// navigation_drawer_inflator.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dragAndDrop="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.widget.DrawerLayout>
// navigation_drawer_inflator_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_drawer_fragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginTop="56dp"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
Finally if you will implement this - You will be able to insert navigation drawer to any activity on run. Cheers :)
Here's how I did it. Create the helper class. I also added some optional code for the ability to finish() the class.
public class NavDrawerHelper extends ContextWrapper{
public NavDrawerHelper(Context context){
super(context);
}
public void initNav(final DrawerLayout drawerLayout, NavigationView navigationView, Toolbar toolbar, final boolean isFinish){
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id){
case R.id.nav_home:
startActivity(new Intent(getBaseContext(), MainActivity.class));
if (isFinish) ((Activity)getBaseContext()).finish();
drawerLayout.closeDrawers();
break;
case R.id.nav_settings:
startActivity(new Intent(getBaseContext(), SettingsActivity.class));
if (isFinish) ((Activity)getBaseContext()).finish();
drawerLayout.closeDrawers();
break;
}
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(((Activity)getBaseContext()),drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
}
then add this code to all activities. This replaces your existing initNavigationDrawer() method.
public void initNavigationDrawer() {
//views
NavigationView navigationView = findViewById(R.id.navigation_view);
DrawerLayout drawerLayout = findViewById(R.id.drawer);
NavDrawerHelper navDrawerHelper = new NavDrawerHelper(this);
navDrawerHelper.initNav(drawerLayout, navigationView, toolbar, false);
}

Categories

Resources