Home > Blockchain >  How to do I navigate to a fragment when I click on a cardview
How to do I navigate to a fragment when I click on a cardview

Time:12-29

I am practicing Kotlin, I'm trying to navigate to a fragment when I click on a cardView.

Please show some patience and understaning I'm new, cos I don't even know how to ask this, even though I know what I want to do..

I think I need to create a function like this:

private fun CardView.setOnClickListener(function: () -> Unit) {

}

But I don't know what argument I'll pass. This is two of the CardView I want to be able to click:

<androidx.cardview.widget.CardView
    android:id="@ id/ways_teach_people_what_you_know"
    android:layout_width="250dp"
    android:layout_height="350dp"
    app:cardElevation="8dp"
    app:cardCornerRadius="12dp"
    android:layout_marginTop="50dp"
    android:layout_margin="30dp"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:clickable="true"
    android:focusable="true">

<androidx.cardview.widget.CardView
    android:id="@ id/ways_show_people_how_to_do_things"
    android:layout_width="250dp"
    android:layout_height="350dp"
    app:cardElevation="6dp"
    app:cardCornerRadius="12dp"
    android:layout_margin="30dp"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:clickable="true"
    android:focusable="true">

And want to navigate those cardViews to these fragments;

import androidx.fragment.app.Fragment

class WaysTeachPeopleWhatYouKnowFragment : Fragment(R.layout.fragment_ways_teach_people_what_you_know) {

}


import androidx.fragment.app.Fragment

class WaysShowPeopleHowToDoThingsFragment : Fragment(R.layout.fragment_ways_show_people_how_to_do_things) {

}

I didn't add the .xml file of the fragments I want to navigate to, it's empty right now, but please if you need it I can add it.

Please I'd like to use findViewByID when referencing the CardView.

If I don't need to create a function, or you know another I can navigate to fragment when I click on the cardView, I'm more than happy to learn it.

I'd appreciate some sample code, And please make it easy for me to understand and understand so I can add the other cardView and fragments I want to navigate to.. Thanks for help in Advance.

CodePudding user response:

I'd made a lot of changes to the App, watch this video, it helped me.

CodePudding user response:

if you are using navController then In Activity

CardView.setOnClickListener{

findNavController(R.id.nav_host_fragment).navigate(R.id.your_destination_fragment)}

In Fragment

CardView.setOnClickListener{

findNavController().navigate(R.id.your_destination_fragment)}

  • Related