我是Android和Java开发的新手,所以请耐心等待我:)我正在尝试获取手机的GPS坐标,然后用纬度更新TextView(我现在只需要纬度)。这就是我到目前为止所拥有的:
main.xml:
[...]
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get my location"
android:id="@+id/button2"
android:layout_gravity="center_horizontal"
android:onClick="returnMyCoordinates" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="This is where the lat value will show up"
android:id="@+id/latitudeResult" />
MapsActivity.java:
public void returnMyCoordinates(View v, Location location){
double latiTude;
latiTude = location.getLatitude();
String lat_value;
lat_value = Double.toString(latiTude);
TextView latView = (TextView) findViewById(R.id.latitudeResult);
latView.setText(lat_value);
}
据我所知,我无法结合&#34;查看v&#34;与Method声明中的其他参数一起使用。如果这是真的,那为什么呢?我怎么能做到这一点?
以下是上下文的整个文件:
package com.example.googlemapsandroidapi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener{
private GoogleMap mMap = null;
protected LocationManager locationManager;
Double lat;
Double long1;
TextView txtLat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void returnMyCoordinates(View v, Location location){
double latiTude;
latiTude = location.getLatitude();
String lat_value;
lat_value = Double.toString(latiTude);
TextView latView = (TextView) findViewById(R.id.latitudeResult);
latView.setText(lat_value);
}
public void showLocation(View v) {
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 250000, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 250000, 0, this);
if(mMap!=null){
mMap.setMyLocationEnabled(true);
}
Log.e("TAG","Location Manager Called Successfully.");
}catch (SecurityException e){
e.printStackTrace();
Log.e("TAG","SecurityException:"+e.getMessage());
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 250000, 0, MapsActivity.this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 250000, 0, MapsActivity.this);
if(mMap!=null){
mMap.setMyLocationEnabled(true);
}
Log.e("TAG","Location Manager Called Successfully.");
}catch (SecurityException e){
e.printStackTrace();
Log.e("TAG","SecurityException:"+e.getMessage());
}
} else {
Toast.makeText(MapsActivity.this,"Sorry We Need All Permissions Open App Again and Allow All.",Toast.LENGTH_LONG).show();
MapsActivity.this.finish();
}
return;
}
}
@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));*/
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}
答案 0 :(得分:1)
尝试初始化TextView latView = (TextView) findViewById(R.id.latitudeResult);
方法中的onCreate
,因为我认为您的MapsActivity.java
是一项活动?你可以用任何一种方式发布整个MapActivity.java
。
答案 1 :(得分:0)
请使用所有课程尝试此操作。 MainActivity.class:
public class MainActivity extends Activity implements
ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener {
protected GoogleApiClient mGoogleApiClient;
protected Location location;
protected boolean mAddressRequested;
protected String mAddressOutput;
private AddressResultReceiver mResultReceiver;
ProgressBar mProgressBar;
private Button btnCurrentLocation, btnShowAddress;
private TextView tvSetLat, tvSetLang, tvAddress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setId();
setListener();
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
updateValuesFromBundle(savedInstanceState);
buildGoogleApiClient();
}
private void setId() {
tvSetLat = (TextView) findViewById(R.id.tvSetLat);
tvSetLang = (TextView) findViewById(R.id.tvSetLang);
btnCurrentLocation = (Button) findViewById(R.id.btnCurrentLocation);
}
private void setListener() {
btnCurrentLocation.setOnClickListener(this);
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle connectionHint) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available, Toast.LENGTH_LONG).show();
return;
}
if (mAddressRequested) {
startIntentService();
}
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
@Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
protected void showToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(ADDRESS_REQUESTED_KEY, mAddressRequested);
savedInstanceState.putString(LOCATION_ADDRESS_KEY, mAddressOutput);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnCurrentLocation:
if (location != null) {
tvSetLat.setText(String.valueOf(location.getLatitude()));
tvSetLang.setText(String.valueOf(location.getLongitude()));
}
break;
default:
break;
}
}
}
你的xml是activity_main
<LinearLayout 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:orientation="vertical"
tools:context="com.example.android.geocoderdemo.MainActivity">
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<TextView
android:id="@+id/tvSetLat"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".50"
android:padding="10dp"
android:text="set lat" />
<TextView
android:id="@+id/tvSetLang"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".50"
android:padding="10dp"
android:text="set long" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<Button
android:id="@+id/btnCurrentLocation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".50"
android:gravity="center"
android:text="Get Current Location" />
</LinearLayout>
并在menifest中添加权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
还要在gradle中添加playservice。
compile 'com.google.android.gms:play-services:9.4.0'
你可以看到我的应用程序gradle。
apply plugin: 'com.android.application'
android { compileSdkVersion 24 buildToolsVersion&#34; 24.0.1&#34;
defaultConfig {
applicationId "com.example.android.geocoderdemo"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
依赖{ 编译fileTree(包括:[&#39; * .jar&#39;],dir:&#39; libs&#39;) testCompile&#39; junit:junit:4.12&#39; 编译&#39; com.android.support:multidex:1.0.0&#39; 编译&#39; com.android.support:appcompat-v7:24.1.1&#39; 编译com.google.android.gms:play-services:9.4.0&#39; }