Search code examples
androidcode-duplication

How to avoid duplicate code in the activity and fragment?


When an activity is launched, the condition is checked in it, if the condition is true, the openNewActivity method is called and the current activity ends. But if the condition is false, then a transition is made to the fragment, inside which this condition can become true and then you need to call the openNewActivity method, which is defined in the activity. I do not want to duplicate this method in the fragment, how to properly implement a call to this method from the fragment? What are the best practices in such cases?


Solution

  • Activity

    class FirstActivity : AppCompatActivity(), MyInterface {
    
         override fun onSomethingDone() { //This function gets called when the condition is true
            openNewActivity()
         }
    
    
         override fun onAttachFragment(fragment: Fragment) { //A fragment MUST never know it's an activity, so we exposed fragment interface member to easily initialize it whenever the fragment is attached to the activity.
             when (fragment) {
                  is MyFragment -> fragment.myInterface = this
                }
    
          }
    
         override fun onCreate() {
              super.onCreate()
          }
    
    
        private fun openNewActivity() {
            //opens a new activity    
        }
    
    }
    

    Interface

    interface MyInterface {
         fun onSomethingDone()
    }
    

    Fragment

    class MyFragment : Fragment() {
       var myInterface: MyInterface? = null
    
    
     override fun onCreate() {
         if (somethingIsTrue)
             myInterface.onSomethingDone() //condition is true, call the interface method to inform the activity that the condition is true and the new activity should be opened.
       }
    
    }
    

    Create an interface. Initialize the fragment's interface in the activity's onAttachFragment for the reason mentioned in the code. This way, the function for starting a new activity is defined only in the activity and does not need to be duplicated in the fragment.