簡體   English   中英

ForYouFragment 片段不更新

[英]ForYouFragment Fragment doesn't update

嗨,我在應用程序啟動時對我的 forYou 片段進行了權限檢查,並且您授予權限,它會進行 api 呼叫並為您獲取當前位置的天氣問題是我必須切換片段以獲取呼叫並再次切換以顯示它在reclyerview中的問題是當我授予它不執行api的位置的權限之后,我必須刷新片段

    fusedLocationClient.lastLocation.addOnSuccessListener(requireActivity()) { location ->
        if (location != null) {
            currentLocation = location
            val currentLatLng = LatLng(location.latitude, location.longitude)
            val currentAddress = getAddress(location.latitude, location.longitude)
            Log.d("TAG", "klagenfurt : ${currentAddress}")
            retrofitOneCallResponse(location.latitude, location.longitude, currentAddress)
            dataService.getFavorites(this)

        }


    }
    if (ActivityCompat.checkSelfPermission(
            requireContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        ActivityCompat.requestPermissions(
            requireActivity(),
            arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
            MapViewFragment.LOCATION_PERMISSION_REQUEST_CODE
        )

        return
    }

創建一個這樣的方法。

private fun getLocation(){
fusedLocationClient.lastLocation.addOnSuccessListener(requireActivity()) { location ->
        if (location != null) {
            currentLocation = location
            val currentLatLng = LatLng(location.latitude, location.longitude)
            val currentAddress = getAddress(location.latitude, location.longitude)
            Log.d("TAG", "klagenfurt : ${currentAddress}")
            retrofitOneCallResponse(location.latitude, location.longitude, currentAddress)
            dataService.getFavorites(this)
        }else{
         getLocation()
        }
    }
}

然后從這里

if (ActivityCompat.checkSelfPermission(
            requireContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        requestPermissions(
            arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
            MapViewFragment.LOCATION_PERMISSION_REQUEST_CODE
        )
    }else{
      getLocation()
}


override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray): Unit {
      if(requestCode==MapViewFragment.LOCATION_PERMISSION_REQUEST_CODE){
          if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
              getLocation();
          }
      }
}

此外,覆蓋片段中的onRequestPermissionsResult 並檢查權限是否授予調用getLocation()

在此處輸入圖像描述它說,並且您在 requestpermisson 行上編寫沒有 ActivityCompat 的代碼它不起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM