Android Google Maps Fragment - java

I have created a new Android project with a Google Map activity defined as
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
The Layout is this
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alewe.myapplication.MapsActivity" />
The problem is :
i have created another activity and im trying to add the google map fragment inside it.
Using the
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.firstLayout,this,this.getTag());
doesnt work because i cant cast FragmentActivity to Fragment.
How can i add the google maps fragment just created inside another activity ?
Thanks

Change your layout (activity_maps) like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alewe.myapplication.MapsActivity"
android:id="#+id/main_view_map">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/button"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="10dp"
app:fabSize="mini"
app:srcCompat="#drawable/ic_refresh_black_24dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp" />
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
And don't use
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.firstLayout,this,this.getTag());
this code.

Related

Add toolbar and drawer menu to Android Google Maps Activity

I have created a standard Google Maps Activity in my app in Android Studio and the map works as expected.
My Activity is called 'NativeMap' and then the activity starts I see a ToolBar/AppBar at the top of the activity with the text "NativeMap".
The layout file for the activity is standard and calls a maps fragment:
<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NativeMap">
</androidx.fragment.app.FragmentContainerView>
As such, there is no toolbar defined in the XML for me to reference or customize...
The onCreate for this activity seems very simple as well, so again I can only assume that there is a lot of stuff included in the background.
// public class NativeMap extends FragmentActivity implements OnMapReadyCallback {
public class NativeMap extends AppCompatActivity implements OnMapReadyCallback {
private static final String TAG = NativeMap.class.getSimpleName();
private GoogleMap mMap;
private ActivityNativeMapBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityNativeMapBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
(Note that I have switched this class to extend AppCompatActivity to get the bar to appear at the top, when it extends FragmentActivity no top bar appears at all.)
How can I access this toolbar or replace it with a standard toolbar.
I also want to add a drawer menu to this activity, but everything looks so abstracted via this fragment inclusion that I have no idea how to.
I've been Googling for about a week now and can't find anything that even seems to point me in the right direction with this.
I figured it out.
androidx.fragment.app.FragmentContainerView can only contain fragments, so the base container in the layout needed to be changed.
I changed it to a <androidx.drawerlayout.widget.DrawerLayout to allow the main menu drawer to be included. (called "_drawer" in the tree view below)
Inside the DrawerLayout I added a androidx.constraintlayout.widget.ConstraintLayout to contain the main layout components, including the map fragment and the toolbar. (The contraint layout is called "mainLayout" in the treeview below)
The toolbar was then added inside a com.google.android.material.appbar.AppBarLayout.
The map fragment was then added in a <fragment> tag below the AppBarLayout.
This works as expected.
The layout XML is now as follows:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="#+id/_drawer"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/mainLayout"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/top_logo"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:contentDescription="#string/app_logo"
app:srcCompat="#drawable/ic_app_top_logo" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout"
tools:context=".NativeMap" />
</androidx.constraintlayout.widget.ConstraintLayout>
<LinearLayout
android:id="#+id/_nav_view"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#EEEEEE">
<include
android:id="#+id/drawerMenu"
layout="#layout/drawer_main" />
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>

RecyclerView doesn't Show Data When Adding two fragments to FragmentManager

I have 2 fragments with recyclerview. InteractionsFragment and its copy InteractionsFragmentCopy (exact same replica of InteractionsFragment). When I try to add them, only the one that gets added first its recyclerview data is displayed, the other fragment's recyclerview data is blank as shown on the screenshot:
---Activity code---
public class HomeActivity extends AppCompatActivity {
private InteractionsFragment interactionsFragment = InteractionsFragment.newInstance();
private InteractionsFragmentCopy interactionsFragmentCopy = InteractionsFragmentCopy.newInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container1, interactionsFragment).show(interactionsFragment).commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container2, interactionsFragmentCopy).show(interactionsFragmentCopy).commit();
}
}
---Layout file---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activities.HomeActivity"
android:background="#color/Blue">
<FrameLayout
android:id="#+id/fragment_container1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_margin="16dp"
android:orientation="vertical"
app:layout_constraintHeight_default="percent"
app:layout_constraintHeight_percent=".9"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toStartOf="parent"
android:background="#color/Yellow">
</FrameLayout>
<FrameLayout
android:layout_margin="16dp"
android:background="#color/Yellow"
android:id="#+id/fragment_container2"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical"
app:layout_constraintHeight_default="percent"
app:layout_constraintHeight_percent=".9"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toStartOf="parent">
</FrameLayout>
</LinearLayout>
Any idea why this is happening?
I have the answer here
answer
It turned out that since I'm using viewpager inside the fragment then I hade to change the viewpager adapter instantiation from:
InteractionsFragment.ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
to
InteractionsFragment.ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
That's fixed the issue

Place button on top right of google maps API [duplicate]

This question already has answers here:
Android, How to create option Menu
(11 answers)
Closed 6 years ago.
I am unable to figure out how to place a button on the top right of the screen on Google Maps Activity I am new to Android development and am unable to find a straight forward explanation on how to do this. My main activity code looks like this:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private final LatLng LOWER_WEST_BOUND = new LatLng(45.427882, 13.347119);
private final LatLng UPPER_EAST_BOUND = new LatLng(46.904552, 16.664808);
private final LatLng LJUBLJANA = new LatLng(46.052771, 14.503602);
private final LatLngBounds SLOVENIJA_OUTER_BOUNDS = new LatLngBounds(LOWER_WEST_BOUND, UPPER_EAST_BOUND);
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(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;
mMap.setLatLngBoundsForCameraTarget(SLOVENIJA_OUTER_BOUNDS);
mMap.addMarker(new MarkerOptions().position(LJUBLJANA).title("Marker in Ljubljana"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LJUBLJANA, 15));
}
}
Desired app look:
https://i.stack.imgur.com/n2FXF.png
My .xml file looks like this:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context="com.fri.studentskaprehrana.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"
tools:layout="#layout/place_autocomplete_fragment" />
The location where you want to place the icon is in the action bar. To place menu items there, refer the menu docs
For the menu, try :
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_button"
android:icon="#drawable/buttonIcon"
app:showAsAction="always"
android:title="Button title" />
</menu>
its very simple and easy
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rr"
>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.fri.studentskaprehrana.MapsActivity" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/a100dp"
android:orientation="horizontal"
android:gravity="right"
android:id="#+id/lll">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Button"
android:id="#+id/button" />
</LinearLayout>
</RelativeLayout>
replace all this code with your code in xml. you can justify it if you want
edit: if you want something like menubar, you can use this design:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.fri.studentskaprehrana.MapsActivity" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#322929">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/imageView40"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="20dp"
android:background="#72c33c" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Your text"
android:id="#+id/textView111"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"
android:textColor="#ffffff" />
</RelativeLayout>
</RelativeLayout>
It's simple.
Add the menu to the activity where you have the fragment and you will have the button there. Add a single menu item only.

Working with Map Fragment Activity

I'm trying to create a basic activity with a google map fragment. Right now I have this:
public class MainScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
// add the map fragment to the activity
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) { return; }
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, new FragmentGoogle()).commit();
}
}
}
public class FragmentGoogle extends android.support.v4.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.map_google, container, false);
}
}
Which is producing this:
My question is: how can I interact with the fragment itself? Let's supposse I want to zoom in Sidney. Should I put the code in the MainScreen.class or in the Fragment.class? Which methods should I use? It's my first time working with fragments.
you don't need to create your own FragmentGoogle. You can use com.google.android.gms.maps.SupportMapFragment and controll it from you activity code.
in the layout:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
and then in the Activity code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
The code is taken from
this tutorial which is enough to start and use most of the features of the Google Maps Android API, just follow the steps :)
Lets say you have an empty activity in a new project.
do this :
creating premade android map activity
And then you ll get something like this :
your project structure
go to google maps api and do what they tell you to do in the (TODO)
Create an account and a project on google maps platform https://console.cloud.google.com/google/maps-apis/
Activate android development by clicking a button you ll have to look for it
and then go to key section to create new api key
go back to android studio and click the yellow xml file in the picture
past your key there
So by now the Map actvity should give you a real map and everything should work , you should see the map if you get to the map activity
but now what you want is to add that map inside your MainActivity .(i named it ActivityMain because MapActivity and MainActivity look the same )
Now all you need to do is copy past the fragment of the xml file activity_maps.xml without changing anything except for the id .
this is the activity_main.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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map1"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />
I tried adding a button here but i couldn't. So what i did is copy the fragment itself and put it inside the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:gravity="center"
tools:context=".ActivityMain">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start" />
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />
</LinearLayout>
I think these are all steps to create the picture you have in your question.
I hope this was useful not painful to read .

How to add map fragment programmatically

I would like add this xml fragment programmatically to other fragments.
Is it possible?
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
In XML you can add a placeholder container:
<FrameLayout
android:id="#+id/mapContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And then in code you can do:
FragmentManager fm = getChildFragmentManager();
SupportMapFragment supportMapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapContainer, supportMapFragment).commit();
Make a layout like:
<FrameLayout
android:id="#+id/layout_mapContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="0"
android:background="#android:color/transparent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent" />
</FrameLayout>
In Activity declare :
FrameLayout mapLayout = (FrameLayout)findViewById(R.id.layout_mapContainer);
initialise map like this:
private void initialiseMap() {
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
SupportMapFragment mFRaFragment = new MapFragmentActivity();
mTransaction.add(mapLayout.getId(), mFRaFragment);
mTransaction.commit();
try {
MapsInitializer.initialize(context);
} catch (Exception e) {
e.printStackTrace();
}
}
Here MapFragmentActivity is class extends SupportMapFragment

Categories