Skip to content

Instantly share code, notes, and snippets.

@mikkipastel
Last active October 6, 2022 08:00
Show Gist options
  • Save mikkipastel/ceb7703aa431966be83ad38343e3da52 to your computer and use it in GitHub Desktop.
Save mikkipastel/ceb7703aa431966be83ad38343e3da52 to your computer and use it in GitHub Desktop.
add second fragment in activity
package com.ascedncorp.androidbasic
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.ascedncorp.androidbasic.databinding.ActivityMainBinding
class MainActivity: AppCompatActivity() {
private val binding: ActivityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, MainFragment.newInstance())
.commit()
}
}
fun openSecondFragment(text: String) {
supportFragmentManager.beginTransaction()
.add(R.id.container, SecondFragment.newInstance(text))
.addToBackStack(null)
.commit()
}
}
package com.ascedncorp.androidbasic
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.ascedncorp.androidbasic.databinding.FragmentMainBinding
class MainFragment: Fragment() {
private lateinit var binding: FragmentMainBinding
companion object {
fun newInstance() = MainFragment()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.button.setOnClickListener {
(requireActivity() as MainActivity).openSecondFragment(binding.edittext.text.toString())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment