android-fragments 如何在片段中获取上下文和MapView

wztqucjr  于 2022-11-13  发布在  Android
关注(0)|答案(2)|浏览(190)

我创建了一个片段,在其中通过editText字段插入数字,作为在另一个类中创建的函数(NavFun类的createPath函数)的参数。我创建的NavFun类有一个构造函数,它接受两个变量,main_activity的上下文和一个mapView。我希望在单击片段中的按钮后调用createPath函数。
如何获取main_activity的上下文和片段中的mapView来创建navFun的示例?
我想在下面的片段中执行类似的操作,但我不知道如何获取上下文和mapView

val navFun: NavFun = NavFun(context, mapView)
navFun.routePath(p1lati, p1long, p2lati, p2long)
navFun.mapView.invalidate()

这是我破碎身体:

// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [CreatePathFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class CreatePathFragment : Fragment() {
    private var param1: String? = null
    private var param2: String? = null

    private lateinit var editTextLatitudineP1: EditText
    private lateinit var editTextLongitudineP1: EditText
    private lateinit var editTextLatitudineP2: EditText
    private lateinit var editTextLongitudineP2: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        val view: View = inflater.inflate(R.layout.fragment_create_path, container, false)

        // create path between editText points
        editTextLatitudineP1 = view.findViewById<EditText>(R.id.editTextLatitudineP1)
        editTextLongitudineP1 = view.findViewById<EditText>(R.id.editTextLongitudineP1)
        editTextLatitudineP2 = view.findViewById<EditText>(R.id.editTextLatitudineP2)
        editTextLongitudineP2 = view.findViewById<EditText>(R.id.editTextLongitudineP2)

        val b = view.findViewById<Button>(R.id.location)
        b.setOnClickListener{
            try {
                Log.d("Clicked", "Clicked")
                val p1lati: Double = editTextLatitudineP1.text.toString().toDouble()
                val p1long: Double = editTextLongitudineP1.text.toString().toDouble()
                val p2lati: Double = editTextLatitudineP2.text.toString().toDouble()
                val p2long: Double = editTextLongitudineP2.text.toString().toDouble()
                println("latitudine p1: $p1lati, longitudine p1: $p1long")
                println("latitudine p2: $p2lati, longitudine p2: $p2long")
                navFun.routePath(p1lati, p1long, p2lati, p2long)
                navFun.mapView.invalidate()
            } catch (e: Exception) {
                Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show()
            }
        }

        // Inflate the layout for this fragment
        return view
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment CreatePathFragment.
         */
        
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            CreatePathFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

这是我的navFun类:

class NavFun(private val context: Context, private val mapView: MapView) {

    private lateinit var road: Road
    val context1: Context = context
    val mapView1: MapView = mapView

    // function to create path between two points
    fun routePath(p1Latit: Double, p1Laong: Double, p2Latit: Double, p2Laong: Double){
        println("inizio")
        val roadManager: RoadManager = OSRMRoadManager(context, "lolloMaps")
        OSRMRoadManager.MEAN_BY_FOOT
        println("passo1 - creoArrayList")
        val waypoints = arrayListOf<GeoPoint>()
        println("passo2 - CreoPuntiEAggiungoInArrayList")
        val startPoint: GeoPoint = GeoPoint(p1Latit, p1Laong) //43.12628, 12.04705
        waypoints.add(startPoint)
        val endPoint: GeoPoint = GeoPoint(p2Latit, p2Laong) //43.12124, 11.97211
        waypoints.add(endPoint)
        println("passo3 - CreoStrada")
        road = roadManager.getRoad(waypoints)

        if (road.mStatus != Road.STATUS_OK){
            Toast.makeText(context, "Errore nel caricamento di road - status = " + road.mStatus, Toast.LENGTH_SHORT).show()
        }
        println("passo4 - CreoPolilinea")
        val roadOverlay: Polyline = RoadManager.buildRoadOverlay(road)
        println("passo5 - AggiungoPolilineaAllaMappa")
        mapView.overlays.add(roadOverlay)
        mapView.invalidate()

        // create checkpoints along the route
        val nodeIcon: Drawable? = ResourcesCompat.getDrawable(mapView.resources, R.drawable.marker_node, null)
        for (i: Int in road.mNodes.indices){
            val node: RoadNode = road.mNodes[i]
            val nodeMarker: Marker = Marker(mapView)
            nodeMarker.position = node.mLocation
            nodeMarker.icon = nodeIcon
            nodeMarker.title = "Passo $i"
            mapView.overlays.add(nodeMarker)

            // add information in checkpoint windows
            nodeMarker.snippet = node.mInstructions
            nodeMarker.subDescription = Road.getLengthDurationText(context,node.mLength, node.mDuration)
            // var icon: Drawable = resources.getDrawable(R.drawable.ic_continue)
            // nodeMarker.image = icon
        }
    }

    // function to add Marker
    private fun mioMarker(lati: Double, longi: Double, i: Int) {
        val pinMarker = Marker(mapView)
        val geoPoint = GeoPoint(lati, longi)
        pinMarker.position = geoPoint
        pinMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
        pinMarker.title = "Title"
        pinMarker.subDescription = "io sono il pin #$i con coordinate $lati, $longi."
        pinMarker.isDraggable = true
        mapView.overlays.add(pinMarker)
        mapView.invalidate()
    }
}

这是我主要活动:

class MainActivity : AppCompatActivity() {

    private var backPressedTime = 0L

    private lateinit var toggle: ActionBarDrawerToggle
    private lateinit var drawerLayout: DrawerLayout

    private lateinit var mapView : MapView
    private lateinit var myLocationNewOverlay: MyLocationNewOverlay
    private lateinit var compassOverlay: CompassOverlay
    private lateinit var mapController: IMapController

    override fun onCreate(savedInstanceState: Bundle?) {
        // disabilita la policy di strictMode nella onCreate per non fare chiamate network in async tasks
        val policy: StrictMode.ThreadPolicy = StrictMode.ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)

        super.onCreate(savedInstanceState)

        //richiesta per gestire i permessi
        requestPermission()

        // inizializza la configurazione di osmdroid, non funziona se non si importa org.osmdroid.config.Configuration.*
        getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this))

        //crea la mappa
        setContentView(R.layout.activity_main)
        mapView = findViewById<MapView>(R.id.map)
        mapView.setTileSource(TileSourceFactory.MAPNIK)
        mapView.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)

        // crea MapController e setta posizione iniziale
        mapController = mapView.controller
        // crea overlay posizione
        myLocationNewOverlay = MyLocationNewOverlay(GpsMyLocationProvider(this), mapView)
        myLocationNewOverlay.enableMyLocation()
        myLocationNewOverlay.enableMyLocation()
        myLocationNewOverlay.isDrawAccuracyEnabled = true
        myLocationNewOverlay.runOnFirstFix { runOnUiThread {
            mapController.animateTo(myLocationNewOverlay.myLocation)
            mapController.setZoom(9.0)
        }
        }
        mapView.overlays.add(myLocationNewOverlay)

        //set user agent
        Configuration.getInstance().userAgentValue = "lolloMaps"

        // controllo
        println(myLocationNewOverlay.myLocation)
        println("creato")

        // attiva bussola, Non Funziona!
        compassOverlay = CompassOverlay(this, InternalCompassOrientationProvider(this), mapView)
        compassOverlay.enableCompass()
        mapView.overlays.add(compassOverlay)

        // attivare griglia latitudine e longitudine
        // val overlay = LatLonGridlineOverlay2()
        // mapView.overlays.add(overlay)

        // abilita gesture rotazione e zoom
        val rotationGestureOverlay = RotationGestureOverlay(mapView)
        rotationGestureOverlay.isEnabled
        mapView.setMultiTouchControls(true)
        mapView.overlays.add(rotationGestureOverlay)

        // abilita mia posizione
        myLocationNewOverlay = MyLocationNewOverlay(GpsMyLocationProvider(this), mapView)
        myLocationNewOverlay.enableMyLocation()
        mapView.overlays.add(myLocationNewOverlay)

        // abilita overlay scala
        val dm : DisplayMetrics = resources.displayMetrics
        val scaleBarOverlay = ScaleBarOverlay(mapView)
        scaleBarOverlay.setCentred(true)
        scaleBarOverlay.setScaleBarOffset(dm.widthPixels / 2, 10)
        mapView.overlays.add(scaleBarOverlay)

        // abilita comandi sulla mappa, single tap e long press
        val mapEventsReceiver: MapEventsReceiverImpl = MapEventsReceiverImpl()
        val mapEventsOverlay: MapEventsOverlay = MapEventsOverlay(mapEventsReceiver)
        mapView.overlays.add(mapEventsOverlay)

        //--------------------------------------------------------------------------------------------

        // codice per menu laterale
        drawerLayout = findViewById(R.id.drawerLayout)
        val navView: NavigationView = findViewById(R.id.nav_view)

        toggle = ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close)
        drawerLayout.addDrawerListener(toggle)
        toggle.syncState()

        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        navView.setNavigationItemSelectedListener {
            it.isChecked = true

            when(it.itemId){
                R.id.nav_create_path -> {
                    Toast.makeText(applicationContext, "Clicked Crea Percorso", Toast.LENGTH_SHORT).show()
                    replaceFreagment(CreatePathFragment(), it.title.toString())
                }

                R.id.nav_saved_paths -> {
                    Toast.makeText(applicationContext, "Clicked Percorsi Salvati", Toast.LENGTH_SHORT).show()
                    replaceFreagment(SavedPathsFragment(), it.title.toString())
                }

                R.id.nav_center_map -> { Toast.makeText(applicationContext, "Clicked Centra Mappa", Toast.LENGTH_SHORT).show()
                    myLocationNewOverlay.runOnFirstFix {
                        runOnUiThread {
                            mapController.animateTo(myLocationNewOverlay.myLocation)
                            mapController.setZoom(9.0)
                            }
                        }
                    }

                R.id.nav_trash -> Toast.makeText(applicationContext, "Clicked Pulisci Mappa", Toast.LENGTH_SHORT).show()
                R.id.nav_settings -> Toast.makeText(applicationContext, "Clicked Impostazioni", Toast.LENGTH_SHORT).show()
                R.id.nav_share -> Toast.makeText(applicationContext, "Clicked Condividi", Toast.LENGTH_SHORT).show()
                R.id.nav_contact_us -> Toast.makeText(applicationContext, "Clicked Contattaci", Toast.LENGTH_SHORT).show()
                R.id.nav_exit -> Toast.makeText(applicationContext, "Clicked Esci", Toast.LENGTH_SHORT).show()
            }
            true
        }

    }

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

    override fun onPause() {
        super.onPause()
        mapView.onPause()
    }

    //funzione per controllare se ho i permessi
    private fun hasPermission() : Boolean {
        // ritorna true quando abbiamo i permessi
        return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
    }

    //funzione per richiedere i permessi
    private fun requestPermission() {
        //aggiungo i permessi ad una lista
        val permission = mutableListOf<String>()
        // se non ho i permessi
        if (!hasPermission()) {
            // aggiungo i permesi alla lista
            permission.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }
        // concede i permessi nella lista
        if (permission.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, permission.toTypedArray(), 0)
        }
    }

    // fragments function
    private fun replaceFreagment(fragment: Fragment, title: String) {
        val fragmentManager: FragmentManager = supportFragmentManager
        val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.frameLayout, fragment)
        fragmentTransaction.addToBackStack(null).commit()
        drawerLayout.closeDrawers()
        setTitle(title)
    }

    // side menu function
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (toggle.onOptionsItemSelected(item)){
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onBackPressed() {
        if (backPressedTime + 2000 > System.currentTimeMillis()) {
            super.onBackPressed()
        }else{
            Toast.makeText(this, "Premere ancora per tornare indietro", Toast.LENGTH_SHORT).show()
        }
        backPressedTime = System.currentTimeMillis()
    }
}
ma8fv8wu

ma8fv8wu1#

您可以通过调用以下内容来使用Fragment中的上下文:context或requireContext(),对于MapView,您必须传递一个值为的变量:findViewById(您的Map视图标识在xml中的R标识)

5anewei6

5anewei62#

我通过如下修改解决了这个问题:

contextMain = activity?.baseContext!!
mapView = activity?.findViewById<MapView>(R.id.map)!!

这样我就可以初始化navFun类并调用createPath函数使其工作。

相关问题