Androidプログラミングでは新しいですが、collapsingToolbarLayoutを使用するフラグメントクラスでMyLocationボタンを使用することはできません。このコード行でMylocationボタンを追加しました:Google PlayサービスでOnMyLocationButtonClickを使用するには
googleMap.setMyLocationEnabled(true);
私は、公式ドキュメントを読んで、それは言った:
をユーザーがボタンをクリックすると、それがわかっている場合、カメラは、デバイスの現在の位置にマップを中央に配置します。
ボタンが表示されますが、私の場合はボタンを押すと何も起こりません。
どこが間違っていますか?
これは私のフラグメントのクラスコードです:
...
<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" />
...
この:これはマニフェストで許可が
<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>
です:これは私のレイアウトである
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;
}
}
私は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'
...
googleMap.setOnMyLocationButtonClickListener(this);が呼び出されましたか?googleMapがnullである可能性があります。したがって、このコード行は呼び出されません。ブレークポイントを使用してコードをデバッグしてみてください。 – Laura
私は "onMapReady"メソッドで呼び出すと、私はそれがmoveCameraを呼び出すことができるので、nullではないと思う。 'この= {PlaceFragment @ 6434} "PlaceFragment {f7320ff#1、ID = 0x7f0d007a}" Googleマップ= {Googleマップ6471 @} currentPosition = {緯度経度@: EDIT これは私がデバッガで見るものです6909} "lat/lng:(55.xxxxx、9.xxxxxx)" – BitRulez
リスナーを設定した場所でクリックリスナーを直接実装してください:googleMap。setOnMyLocationButtonClickListener(新しいOnMyLocationButtonClickListener(){ \t \t \t @Override \t \t \t公共ブールonMyLocationButtonClick(){ \t \t \t \t Toast.makeText( getActivity()、 "クリックされたボタン!"、Toast.LENGTH_SHORT ).show(); trueを返す; } \t \t \t}); – Laura