0

I am using the Navigation functionality of the JetPack library.

Included Two Fragments in Navigation Graph.

Have to navigate from TitleFragment to GameFragment with the click of the button which is inside TitleFragment.

I have done as below inside TitleFragment to take the click of that button :

binding.playButton.setOnClickListener {
        Navigation.createNavigateOnClickListener(R.id.action_titleFragment_to_gameFragment)
        //Navigation.findNavController(it).navigate(R.id.gameFragment)
    }

where action_titleFragment_to_gameFragment is action id.

Used createNavigateOnClickListener method but its not working. Instead commented the second line is working.

What might be the issue with Navigation.createNavigateOnClickListener(R.id.action_titleFragment_to_gameFragment)

Content of Navigation Graph is as below :

 <fragment
    android:id="@+id/titleFragment"
    android:name="com.example.android.navigation.TitleFragment"
    android:label="fragment_title"
    tools:layout="@layout/fragment_title" >
    <action
        android:id="@+id/action_titleFragment_to_gameFragment"
        app:destination="@id/gameFragment" />
</fragment>
<fragment
    android:id="@+id/gameFragment"
    android:name="com.example.android.navigation.GameFragment"
    android:label="fragment_game"
    tools:layout="@layout/fragment_game" />
Jaimin Modi
  • 1,530
  • 4
  • 20
  • 72

1 Answers1

2

You can set a clicklistener on a view in android by following two patterns,

  • By passing an instance of a class implementing View.OnClickListener where you override the OnClick method
  • Since View.OnClickListener is a SAM, you can pass a lambda instead of implementing the View.OnClickListener interface.

button.setOnClickListener{ ... } expecting a lambda and button.setOnClickListener( ... ) expects an instance of View.OnClickListener.

So in your case, since Navigation.createNavigateOnClickListener returns object of type View.OnClickListener use round brackets - () and not curly brackets - {}

Sekiro
  • 1,537
  • 1
  • 7
  • 21