What would be the best practices to test this Fragment? - android

Lets suppose I have a fragment class like this one below named EmailSearchResultPageFragment().
class EmailSearchResultPageFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_email_search_result_page, container, false)
someFunctionThatRequiresViewFromOnCreate(view)
showPage(fragment)
return view
}
fun someFunctionThatRequiresViewFromOnCreate(view: View) {
view.DoSomethingWithView(view)
}
fun showPage(fragment: Fragment) {
fragmentManager!!.beginTransaction().addToBackStack(null).replace(R.id.container, fragment).commit()
}
}
If i want to unit test someFunctionThatRequiresViewFromOnCreate(:), and showPage(:) what would be the best practice ??
How can I possibly mock view and fragment that is being instantiated inside onCreate???!

Related

Difference between onCreateView and onViewCreated in Fragment - Kotlin

I know this question has been asked many times but just wanted to have some more clarity.
So I wanted to create a simple fragment with a button that should change the fragment when clicked - very simple and basic one.
hence I create a function, and called it on onCreateView. Nothing happeded.
Then I created onViewCreated after onCreateView and called the same function in it.
It Worked.
My Question is What exactly made it work ?
here is the code
class homeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
hello()
}
fun hello()
{
val button = view?.findViewById<Button>(R.id.button_login)
button?.setOnClickListener{
val action = homeFragmentDirections.actionHomeFragmentToLoginFragment()
findNavController().navigate(action)
Toast.makeText(context,"wao",Toast.LENGTH_LONG).show()
}
}
}
As per your comments, you did something like this:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home, container, false)
hello() // the method has already returned a View, so this call is never reached.
}
So, when you call hello() in onCreateView after the return statement,
the method has no effect because of the return statement.
Since onViewCreated is called after the onCreateView,
the underlying View is no more null in your hello function.
If you still want to use onCreateView, you can do something like this:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val fragmentView = inflater.inflate(R.layout.fragment_home, container, false)
hello(fragmentView)
return fragmentView
}
fun hello(buttonHolderView: View?) {
val button = buttonHolderView?.findViewById<Button>(R.id.button_login)
button?.setOnClickListener {
val action = homeFragmentDirections.actionHomeFragmentToLoginFragment()
findNavController().navigate(action)
Toast.makeText(context, "wao", Toast.LENGTH_LONG).show()
}
}
You need to inflate the view before calling the function:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val fragmentHome = inflater.inflate(R.layout.fragment_home, container, false)
hello(fragmentHome)
return fragmentHome;
}
Change your hello function:
fun hello(view: View)
{
....

How to return multiple values VIEW in Kotlin?

I was trying to change ImageView in one Fragment from another Fragment. But since this cannot be done without container, I have to create another view value with the inflater method. Then I need to return these view values with the inflater methods. How do I return two views?
code is written in a fragment:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.firstfragment, container, false)
val view2 = inflater.inflate(R.layout.secondfragment, container, false)
val imgPF: ImageView = view2.findViewById(R.id.imageView)
imgPF.setImageResource(R.drawable.image_29)
view.ButtonFromFirstFragment.setOnClickListener{
//Unimportant code
}
setHasOptionsMenu(true)
return view //Approximately here i need to return two views, but how?
//And can it be done somehow differently?
}
Basically you should not have 2 fragments within a fragment. Please double check that you are not confusing fragments with views.
If you want to have those 2 fragments in an activity and you are showing both of your fragments at the same time then you should have 2 separate fragments:
Fragment A:
(...)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.firstfragment, container, false)
view.ButtonFromFirstFragment.setOnClickListener{
//Unimportant code
}
return view
}
(...)
Fragment B:
(...)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.secondfragment, container, false)
val imgPF: ImageView = view.findViewById(R.id.imageView)
imgPF.setImageResource(R.drawable.image_29)
return view
}

BaseFragment with viewbinding in android

I have created a BaseFragment to inflate other fragment's layout using view binding.
I have setup everything but getting an issue mViewBinding is not initialized. Guide me in the right direction.
BaseFragment.kt:
abstract class BaseFragment<VM : ViewModel, VB : ViewBinding> : Fragment() {
protected abstract val mViewModel: VM
protected lateinit var mViewBinding: VB
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mViewBinding = getViewBinding(inflater, container)
return mViewBinding.root
}
abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB
}
DemoFragment.kt:
class DemoFragment : BaseFragment<DemoBaseViewModel, FragmentDemoBinding>() {
override val mViewModel: DemoBaseViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return mViewBinding.root
}
override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentDemoBinding {
return FragmentDemoBinding.inflate(inflater, container, false)
}
}
With a design like this, your derived class onCreateView() should call to base class super.onCreateView() where the binding is initialised.
Or as Primož Ivančič points out, you don't need to override onCreateView() at all.

How to change image in activity from fragment in Kotlin

In an android app I have an activity with several fragments. In one of these fragments I have an ImageButton. On click I want to let something happen in the activity directly, not in the fragment. In this case I want to set an image. Summed up, the ImageButton is in the fragment, but the ImageView I want to change on click is in the activity.
How do I achieve that? Whatever I've tried resulted in an app crash.
This is how my fragment.kt looks:
class Fragment1 : Fragment() {
companion object{
fun newInstance() = Fragment1()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_1, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
imageButton.setOnClickListener{
imageView.setImageResource(R.drawable.example)
}
}
}
class Fragment1 : Fragment() {
var callbacks: OnFragmentCallbacks? = null
override fun onAttach(context: Context?) {
super.onAttach(context)
callbacks = activity as OnFragmentCallbacks
}
interface OnFragmentCallbacks{
fun changeImage(resourceId: Int)
}
companion object{
fun newInstance() = Fragment1()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_1, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
imageButton.setOnClickListener{
callbacks?.changeImage(R.drawable.example)
}
}
In your Activity:
// Change FragmentName with name of your Fragment class
class MainActivity : AppCompatActivity(), FragmentName.OnFragmentCallbacks{
override fun changeImage(resouseId: Int){
imageView.setImageDrawable(getResources().getDrawable(resourceId))
// or
imageView.setImageResource(resourceId)
}
Just coded it in stackoverflow, may not be perfect

How do I correctly use Kotlin to call a blank fragment from the Home fragment?

class HomeFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_home, container, false)
val fab = v.findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
val blankFragment = BlankFragment()
val manager = childFragmentManager
manager.beginTransaction().replace(R.id.frame_container, blankFragment, blankFragment.tag).commit()
// System.out.println("You have reached the floating action button")
}
return v
}
}
Getting a no view found error. I may have issues with the R.id.frame_content but Kotlin doesn't immediately identify all id values...
This may not be the best way and I apologize for the horrible formatting I does this while answer out on my phone and it's hard to get it perfect. Anyways In the activity that holds your fragments, such as MainActivity.kt add...
supportFragmentManager.beginTransaction.add(R.id.fragment_home, HomeFragment.newInstance, "HomeFragment").commit()
In your HomeFragment.kt change the following.
class HomeFragment: Fragment(){
companion object {
fun newInstance(): HomeFragment{
return HomeFragment() }
fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater!!.inflate(R.layout.fragment_home, container, false)
val activity = activity
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val clickListener = View.OnClickListener { view ->
when (view.getId()) {
R.id.fab -> NextFragment()
}
}
fab.setOnClickListener(clickListener)
}
NextFragment(){
val fragManager = activity?.supportFragmentManager
fragManager?.beginTransaction()?.replace(R.id.frame_container, BlankFragment.newInstance(), "blankFragment")?.commit()
}
Make sure you make the same changes to BlankFragment.kt
class BlankFragment: Fragment(){
companion object {
fun newInstance(): BlankFragment{
return BlankFragment() }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater!!.inflate(R.layout.fragment_blank, container, false)
val activity = activity
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Do some stuff with your views in BlankFragment here
}
}

Categories

Resources