有没有办法使用 Kotlin 获取片段中的位置,我已经研究了获取位置的方法,但他们都在活动中做到了。有没有办法获取片段中的位置?使用 Kotlin?
在活动或片段中做事是一样的。
只需从 onCreate of MainActivity 移动到 onActivityCreate of fragment。
当然,必须在活动中检查权限,因为它们需要上下文,并且在片段中这样做会很奇怪,但是所有代码和UI内容都可以在片段本身中完成。
更好的解释。
主要活动
-
在主活动中请求权限
override fun onCreate(savedInstanceState: Bundle?( { super.onCreate(savedInstanceState( 设置内容视图(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() } } }
如果已经授予权限,请替换将显示数据的片段,如果没有,请请求权限。
-
权限结果
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()
}
}
}
片段将使用 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
我得到纬度和经度
注意:我放置了空检查,因为如果您不这样做,您会注意到值有可能为空