Gurmukh Singh
Gurmukh Singh

Reputation: 2017

Button Click to change view in Fragment - Kotlin

I have the following:

class SettingsFragment : Fragment() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_settings, container, false)
    val auth = FirebaseAuth.getInstance()

    signOutButton.setOnClickListener{
        Log.i("TAG", "logout tapped")
        auth.signOut()
        startActivity(Intent(activity,LoginActivity::class.java))
    }
}
}

The view loads, but when I tap the button to log the user out, I dont see a print out of the log and nor does the user logout and the view doesn't switch to the loginActivity().

My button:

<Button
    android:id="@+id/signOutButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sign out" />

Upvotes: 0

Views: 632

Answers (2)

Umair Saeed
Umair Saeed

Reputation: 86

override the onViewCreated() function and write down your signout code there, Also initialize the signOutButton.

Upvotes: 0

Xid
Xid

Reputation: 4951

As you have already returned the view the rest of the lines will never be called. It's unreachable. return be at the end of the function. Also, you will want to set the click listener after the view is created(onViewCreated) else you will get a NullPointerException.

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_settings, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    
    val auth = FirebaseAuth.getInstance()

    signOutButton.setOnClickListener{
        Log.i("TAG", "logout tapped")
        auth.signOut()
        startActivity(Intent(activity,LoginActivity::class.java))
    }
}

Upvotes: 1

Related Questions