使用 this@MapsActivity 传递上下文时如何修复 "Unresolved reference"

How to fix "Unresolved reference" when passing context with this@MapsActivity

问题总结

我试过的

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="gr.mantis_project.obdLogger">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <application
        <activity
                android:name="gr.example.obdLogger.SplashActivity"
                android:label="@string/title_activity_maps"
                android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
                android:name="gr.example.obdLogger.MapsActivity">
        </activity>
    </application>
</manifest>

MapsActivity.kt

package gr.example.obdLogger

class MapsActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMapClickListener {
    override fun onMapReady(p0: GoogleMap?) {
    }
    override fun onMapClick(p0: LatLng?) {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivitymainBinding =
            DataBindingUtil.setContentView(this, R.layout.mapsactivity)
        setSupportActionBar(findViewById(R.id.toolbar))
    }

mapFragment.kt

package gr.example.obdLogger

class MapFragment : Fragment(), OnMapReadyCallback {

    private lateinit var mMapView: MapView
    private lateinit var mMap: GoogleMap
    private lateinit var mView: View
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var lastLocation: Location

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mMapView.onSaveInstanceState(outState)
        isGpsEnable()  
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_map, container, false)

        mMapView = view?.findViewById(R.id.mapview) as MapView
        mMapView.onCreate(savedInstanceState)
        mMapView.getMapAsync(this)

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireContext())


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
        mMapView.onResume()
    }

    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap
        mMap.uiSettings.isZoomControlsEnabled = true      
    }

    companion object {
        private const val LOCATION_PERMISSION_REQUEST_CODE = 1
    }

    private fun isGpsEnable(): Boolean {
        if (ActivityCompat.checkSelfPermission(
                requireContext(),   // **This works**
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this@MapsActivity, // **This is unresolved**
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ),
                LOCATION_PERMISSION_REQUEST_CODE
            )
        } else {
            Log.e("DB", "PERMISSION GRANTED")
        }
        return true
    }
}

不行。 MapsActivity 不是片段的外部范围。您可以阅读更多关于合格的 this here

MapFragmentMapsActivity[=没有内部依赖32=],所以你不能引用 MapsActivity 作为外部引用。外部引用仅适用于内部 类(请注意,lambda 函数是匿名内部类,因此您也可以在那里使用 this@ 来引用外部范围)。如果您的应用程序需要上下文,您可以在 MapFragment 中调用 nullsafe requireContext() 方法或引用 [=27= 的实例]MapsActivity

    (activity as MainActivity)

片段可以通过其 属性 activity 访问它附加的 activity 这就是 (activity as MainActivity) 有效的原因

在处理可为 null 的值时,我喜欢使用 ?用 let 链接的运算符,例如 context?.let{ doStuff(it) } 这样你就不会得到 nullptr 异常了