Ich bin neu in der Android-Programmierung. Ich kann die MyLocation-Schaltfläche in meiner Fragmentklasse nicht verwenden, die ein collapsingToolbarLayout verwendet. Ich habe die Mylocation-Schaltfläche mit dieser Codezeile hinzugefügt:So verwenden Sie OnMyLocationButtonKlicken Sie mit Google Play Services
googleMap.setMyLocationEnabled(true);
las ich die offizielle doc und es sagte:
wenn ein Benutzer auf die Schaltfläche klickt, wird die Kamera die Karte auf den aktuellen Standort des Geräts zentriert, wenn bekannt ist.
Die Schaltfläche erscheint, aber in meinem Fall passiert nichts, wenn ich die Taste drücke.
Wo liege ich falsch?
das ist mein Fragment Klassencode:
public class MapFrag extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMyLocationButtonClickListener {
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LatLng currentPosition;
//
private List<Place> places;
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private RecyclerViewAdapter adapter;
//
//imageLoader – our ImageLoader object which we’ll use to download the images
ImageLoader imageLoader;
private GoogleMap googleMap;
private SupportMapFragment map;
private CollapsingToolbarLayout collapsingToolbarLayout = null;
private static View rootView;
// with image
private static final String ENDPOINT_PLACE = "http://www.mocky.io/v2/xxxxxxxxxxxxxxxx";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
rootView = inflater.inflate(R.layout.fragment_place, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
requestJsonObject();
imageLoader = MySingleton.getInstance(getContext()).getImageLoader();
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
collapsingToolbarLayout = (CollapsingToolbarLayout) rootView.findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle("Map");
toolbarTextAppernce();
enableMapScrolling();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view_id);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
// Inflate the layout for this fragment
return rootView;
}
@Override
public void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
@Override
public void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
private void toolbarTextAppernce() {
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.collapsedappbar);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.expandedappbar);
}
public void setUpMap() {
if (googleMap == null) {
map = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
map.getMapAsync(this);
}
}
/**
* This method enable the possibility for the user to scroll the map
*/
private void enableMapScrolling() {
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) rootView.findViewById(R.id.app_bar_id).getLayoutParams();
AppBarLayout.Behavior behavior = new AppBarLayout.Behavior();
behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
@Override
public boolean canDrag(AppBarLayout appBarLayout) {
return false;
}
});
params.setBehavior(behavior);
}
/**
* 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) {
this.googleMap = googleMap;
if (googleMap != null) {
//noinspection MissingPermission
googleMap.setMyLocationEnabled(true);
googleMap.setOnMyLocationButtonClickListener(this);
addMarkers();
//where map start
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 15));
}
}
/**
* this method add all coordinete point of the json file with a marker to the map
*/
private void addMarkers() {
for (Place place : places) {
googleMap.addMarker(new MarkerOptions().position(place.getCoordinates()).title(place.getName().substring(0, 1).toUpperCase() +
place.getName().substring(1)));
}
}
private void requestJsonObject() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, ENDPOINT_PLACE, onPostsLoaded, onPostsError);
//add request to the queue
MySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
}
private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("PLACE FRAGMENT", "Response: " + response);
GsonBuilder builder = new GsonBuilder();
Gson jsonPlace = builder.create();
places = new ArrayList<>();
places = Arrays.asList(jsonPlace.fromJson(response, Place[].class));
adapter = new RecyclerViewAdapter(getContext(), places);
recyclerView.setAdapter(adapter);
setUpMap();
}
};
private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Snackbar snackbar = Snackbar
.make(rootView, "No internet connection!", Snackbar.LENGTH_INDEFINITE)
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
requestJsonObject();
}
});
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
snackbar.show();
}
};
@Override
public void onConnected(@Nullable Bundle bundle) {
//noinspection MissingPermission
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
currentPosition = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(getActivity(), "BUTTON CLICKED!", Toast.LENGTH_SHORT).show();
return true;
}
}
dies mein Layout ist:
<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"
android:fitsSystemWindows="true"
>
<include layout="@layout/toolbar_layout"/>
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar_id"
android:layout_width="match_parent"
android:layout_height="230dp"
android:fitsSystemWindows="true"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_collapseMode="parallax"/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg_login"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:scrollbars="vertical" />
</android.support.v4.widget.NestedScrollView>
ist dies die Erlaubnis im Manifest:
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...
diese ist mein build.gra dle:
...
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:palette-v7:24.2.1'
compile 'com.android.support:cardview-v7:24.2.1'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.android.volley:volley:1.0.0'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.google.android.gms:play-services-maps:9.8.0'
compile 'com.google.android.gms:play-services-location:9.8.0'
...
Ist googleMap.setOnMyLocationButtonClickListener (this), aufgerufen? Vielleicht googleMap ist null und Daher wird diese Codezeile nicht aufgerufen. Versuchen Sie, einen Breakpoint zu verwenden, um den Code zu debuggen. – Laura
Ich rufe es in "onMapReady" -Methode, und ich denke, ist nicht null, weil ich es moveCamera darauf aufrufen kann. EDIT das ist, was ich im Debugger sehen: 'dieses = {PlaceFragment @ 6434} "PlaceFragment {f7320ff # 1 id = 0x7f0d007a}" googleMap = {GoogleMap @ 6471} current = {LatLng @ 6909} "lat/lng: (55.xxxxx, 9.xxxxxx)" ' – BitRulez
Versuchen Sie, den Klick-Listener direkt dort zu implementieren, wo Sie den Listener gesetzt haben: googleMap.setOnMyLocationButtonClickListener (neu OnMyLocationButtonClickListener() { \t \t \t @Override \t \t \t public boolean onMyLocationButtonClick() { \t \t \t \t Toast.makeText ( getActivity() "GEKLICKT Taste!", Toast.LENGTH_SHORT) .show(); return true; } \t \t \t}); – Laura