End activity from fragment
I'm trying to implement an onboard activity which shows only for the first time of using the app, after it finished it will move to the main activity.
I've made another activity which includes fragments, afterwards I'd like to set a settings on shared-preferences which hold a value that tells if it first time or not.
onboard activity:
class OnboardActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_onboard)
}
fun finishOnBoarding() {
val preferences = getSharedPreferences("my_preferences", MODE_PRIVATE)
preferences.edit()
.putBoolean("onboarding_complete", true).apply()
val main = Intent(this, MainActivity::class.java)
startActivity(main)
finish()
}
}
InitialScreenFragment which is the last fragment in my code:
class InitialScreenFragment : Fragment() {
private var _binding: FragmentInitialScreenBinding? = null
private val binding get() = _binding!!
lateinit var callback: FragmentActivity
override fun onAttach(context: Context) {
super.onAttach(context)
callback = requireActivity();
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentInitialScreenBinding.inflate(inflater, container, false)
val view = binding.root
//finish button which suppose to end the session of boarding
// binding.finishBtn.setOnClickListener{
// callback.finishOnBoarding()
}
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
how can I set the listener on finish button to call my activity method to end the onboard please? thanks
Solution 1:
You may use separate interface as callback
interface OnboardingListener {
fun finishOnboarding()
}
implement this interface in your OnboardActivity
class OnboardActivity : AppCompatActivity(), OnboardingListener {
override fun finishOnboarding(){
val preferences = getSharedPreferences("my_preferences", MODE_PRIVATE)
preferences.edit().putBoolean("onboarding_complete", true).apply()
val main = Intent(this, MainActivity::class.java)
startActivity(main)
finish()
}
}
and for example set it to fragment from your activity
class InitialScreenFragment : Fragment() {
.....
var callback: OnboardingListener? = null
.....
}
val fragment: InitialScreenFragment = InitialScreenFragment()
fragment.callback = this // this should be in OnboardActivity where you create an instance of InitialScreenFragment
and then from your fragment call
callback?. finishOnboarding()