2

I'm working on a simple map app, i used the navigationDrawer to put my map in the first option of the drawer.. now the problem is when i put any button in the same fragment of the map or the same layout it doesn't perform what i want! for example : i need to zoom on my location when i click the button. i tried some solutions i found on the site but there was no luck..

image

xml code :

<android.support.constraint.ConstraintLayout 
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">


   <fragment android:layout_height="match_parent"   
  android:layout_width="405dp" android:id="@+id/mapfragment"

    class="com.google.android.gms.maps.MapFragment"


    android:layout_marginEnd="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginRight="8dp"

/>


<RelativeLayout android:layout_width="wrap_content" 
android:layout_height="wrap_content">
    <Button
        android:id="@+id/bt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="46dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:onClick="onClick"
        />
</RelativeLayout>




</android.support.constraint.ConstraintLayout>

java code :

 public class maptest extends Fragment implements OnMapReadyCallback,View.OnClickListener {
GoogleMap mp;

@Nullable
View v1;

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    Button bt2=(Button)v1.findViewById(R.id.bt1);
    bt2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getActivity(), "ggg", Toast.LENGTH_SHORT).show();
        }
    });


    return inflater.inflate(R.layout.newmapfragment, container,false);

}



@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    MapFragment fragment= (MapFragment) getChildFragmentManager().findFragmentById(R.id.mapfragment);
    fragment.getMapAsync(this);

}

@Override

public void onMapReady(GoogleMap mp) {
    // Add a marker in Sydney, Australia,
    // and move the map's camera to the same location.
    LatLng sydney = new LatLng(31.163937, 35.710373);
    mp.addMarker(new MarkerOptions().position(sydney)
            .title("Marker in Sydney"));
    mp.moveCamera(CameraUpdateFactory.newLatLng(sydney));

   mp.addMarker(new MarkerOptions().position(new 
   LatLng(31.163937,35.710373)).title("mymap")).showInfoWindow();
   mp.animateCamera(CameraUpdateFactory.newLatLngZoom(new 
   LatLng(31.163937,35.710373),16));
   }



   @Override
   public void onClick(View view) {
    Button b = (Button) view.findViewById(R.id.bt1);
    b.setOnClickListener(this);
    LatLng sydney = new LatLng(31.163937, 35.710373);
    mp.addMarker(new MarkerOptions().position(sydney)
            .title("Marker in Sydney"));
    mp.moveCamera(CameraUpdateFactory.newLatLng(sydney));

    mp.addMarker(new MarkerOptions().position(new 
    LatLng(31.163937,35.710373)).title("mymap")).showInfoWindow();
    mp.animateCamera(CameraUpdateFactory.newLatLngZoom(new 
    LatLng(31.163937,35.710373),16));
     }


    }

any help will be appreciated..

4 Answers4

1

You may be forgot in your fragment's onCreateView:

vi=inflater.inflate(your_fragment_layout_xml,container,false);
Jayesh Rathod
  • 600
  • 1
  • 5
  • 18
1

Try this You forgot to inflate in v1 in onCreateView

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    v1=inflater.inflate(your_fragment_layout_xml,container,false);
    Button bt2=(Button)v1.findViewById(R.id.bt1);
    bt2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getActivity(), "ggg", Toast.LENGTH_SHORT).show();
        }
    });


    return v1;

}

EDIT-1

move this in Fragment

Button b = (Button) v1.findViewById(R.id.bt1);
b.setOnClickListener(this);

EDIT-2

remove android:onClick="onClick" from your Button in XML

Goku
  • 9,102
  • 8
  • 50
  • 81
1

Replace your maptest Fragment with below code

public class maptest  extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {
GoogleMap mMap;
double latitude;
double longitude;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
View v1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v1 = inflater.inflate(R.layout.fragment_map, container, false);





    ((SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map)).getMapAsync(this);

    //Check if Google Play Services Available or not
    if (!CheckGooglePlayServices()) {
        Log.d("onCreate", "Finishing test case since Google Play Services are not available");

    } else {
        Log.d("onCreate", "Google Play Services available.");

    }


    Button bt2=(Button)v1.findViewById(R.id.bt1);
    bt2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(mLastLocation!=null  && mMap!=null)
            {

                /////to change map type
                mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                //////to zoom on current location
                LatLng sydney = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                mMap.addMarker(new MarkerOptions().position(sydney)
                        .title("current location"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));



            }


        }
    });


    return v1;
}


@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    MapFragment fragment= (MapFragment) getChildFragmentManager().findFragmentById(R.id.mapfragment);
    fragment.getMapAsync(this);

}




private boolean CheckGooglePlayServices() {
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
    int result = googleAPI.isGooglePlayServicesAvailable(context);
    if (result != ConnectionResult.SUCCESS) {
        if (googleAPI.isUserResolvableError(result)) {
            googleAPI.getErrorDialog((Activity) context, result,
                    0).show();
        }
        return false;
    }
    return true;
}


protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.

    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

}


@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
    Log.d("onLocationChanged", "entered");

    mLastLocation = location;

    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        Log.d("onLocationChanged", "Removing Location Updates");
    }
    Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);




    //Initialize Google Play Services
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

}


@Override
public void onResume() {
    super.onResume();

}

}

kamal verma
  • 496
  • 3
  • 16
  • yes sir.. i need to get any response from my button i mean i to zoom on my location or change the map type (satellite,terrain) i don't get anything from my button it seems it's not connected with any function... – loai ghareeb Dec 01 '17 at 11:08
0

First of all remove any one onclick method cause right now you are using two onclick methods. and you should add button like this :-

    <RelativeLayout android:layout_width="wrap_content" 
    android:layout_height="wrap_content">
        <Button
            android:id="@+id/bt1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="46dp"
            android:text="Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            />
</RelativeLayout>



        View v1;
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) 
        {
        v1 = inflater.inflate(R.layout.newmapfragment, container, false);
            Button bt2=(Button)v1.findViewById(R.id.bt1);
            bt2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(getActivity(), "ggg", Toast.LENGTH_SHORT).show();
                }
            });
            return v1;
        }

Click here! for getting current location.