如何使用 Kotlin 获取片段中的当前经度和纬度?

how to get current longtitude and latitude in fragments using Kotlin?

有没有办法使用 Kotlin 获取片段中的位置,我研究了获取位置的方法,但他们都在 activity 中做到了。有没有办法获取片段中的位置?使用科特林?

在activity或片段中做事都是一样的。

只需从MainActivity的onCreate移动到fragment的onActivityCreated即可。

当然必须在 activity 中检查权限,因为它们需要上下文,并且在片段中这样做会很奇怪,但是所有代码和 UI 东西都可以在片段本身。

更好的解释。

主要ACTIVITY

  1. 在 Main activity 请求许可

    覆盖乐趣 onCreate(savedInstanceState: Bundle?) { super.onCreate(已保存实例状态) setContentView(R.layout.main_activity)

    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
    
        ActivityCompat.requestPermissions(this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            MY_PERMISSIONS_REQUEST_READ_LOCATION)
    
    } else {
    
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, MainFragment.newInstance())
                .commitNow()
          }
       }
    }
    

如果已经授予许可,则替换将显示数据的片段,如果没有,请请求许可。

  1. 权限结果

    if ((grantResults.isNotEmpty() && grantResults[0] == 
          PackageManager.PERMISSION_GRANTED)) {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.container, MainFragment.newInstance())
                    .commitNow()
            } else {
                Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show()
            }
    

    如果获得许可做同样的事情,实例化片段。

片段

private lateinit var fusedLocationClient: FusedLocationProviderClient

companion object {
    fun newInstance() = MainFragment()
}


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    return inflater.inflate(R.layout.main_fragment, container, false)
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity!!.applicationContext)

    fusedLocationClient.lastLocation
        .addOnSuccessListener { location : Location? ->
            if (location != null) {
                lat_view.text = location.latitude.toString()
            }

            if (location != null) {
                long_view.text = location.longitude.toString()
            }
        }
}

Fragment 将使用 FusedLocationProviderClient 获取位置。 如果您想了解更多信息,请看这里:

https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient

https://developer.android.com/training/location/retrieve-current

如何导入包

https://developers.google.com/android/guides/setup

正如您在

中看到的那样
.lastLocation

我得到经纬度

注意:我进行了空值检查,因为您会注意到,如果您不这样做,则值有可能为空值