如何在Google Play服务中使用OnMyLocationButtonClick

时间:2016-11-15 10:09:14

标签: android google-maps android-fragments google-maps-api-3

我是Android编程的新手,我无法在我使用collapsingToolbarLayout的片段类中使用MyLocation按钮,我在这行代码中添加了Mylocation按钮:

googleMap.setMyLocationEnabled(true);

我阅读了官方文件并且说:

  

当用户点击该按钮时,相机会将地图置于设备当前位置的中心位置(如果已知)。

按钮出现,但在我的情况下按下按钮时没有任何反应。

我哪里错了?

这是我的Fragment类代码:

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;
}
}

这是我的布局:

 <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>

这是清单中的权限:

...
<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" />
...

这是我的build.gradle:

...
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'
...

2 个答案:

答案 0 :(得分:3)

工具栏与“我的位置”按钮重叠。您可以尝试使用GoogleMap.setPadding()方法在地图边缘附近添加填充。地图将继续填充整个容器,但文本和控件定位,地图手势和相机移动的行为就像它有放在一个较小的空间里。“ (see Maps Documentation)

mMap.setPadding(200, 200, 200, 200);

或者您可以尝试添加:

android:layout_marginTop="100dp"

在你的xml中,对于MapFragment。

答案 1 :(得分:0)

我用以下代码解决了在onMapReady方法中更改MyButton位置的问题:

// Get the button 

View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                locationButton.getLayoutParams();

layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 30, 30);