Doug Ray
Doug Ray

Reputation: 1010

Android Flavors :Applying only flavor specific code to a source set

I am running into some trouble with source sets, I have a main source set that contains most of the common code but then a build flavor switch was included by the previous developer for example :

    if (Application.inKiosk) {
        navigation.visibility = View.INVISIBLE
        val employeeSelectionFragment = EmployeeSelectionFragment()
        employeeSelectionFragment.setAllList(employees)
        employeeSelectionFragment.setCallback(employeeSelected)
        supportFragmentManager.beginTransaction().add(R.id.small_container, employeeSelectionFragment, "EmployeeSelectionFragment").commitNow()
        currentTimeRecord = TimeRecord()
    } else {
        setupTimeRecords(employees!!.first()!!.id, savedInstanceState == null)
    }

I want to extract this flavor specific block and include it in its own source set folder. I can't get access to the common members though such as navigation. How would I extract this section ?

        navigation.visibility = View.INVISIBLE
        val employeeSelectionFragment = EmployeeSelectionFragment()
        employeeSelectionFragment.setAllList(employees)
        employeeSelectionFragment.setCallback(employeeSelected)
        supportFragmentManager.beginTransaction().add(R.id.small_container, employeeSelectionFragment, "EmployeeSelectionFragment").commitNow()
        currentTimeRecord = TimeRecord()

Upvotes: 2

Views: 1371

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006704

The basic recipe for splitting code between product flavors is to:

  • Set up 2+ flavors in a dimension

  • Create source sets for each of those flavors (src/flavorOne/, src/flavorTwo/)

  • Define some class in both of those flavors

  • Have that class implement functions that offer the per-flavor functionality that you are looking for (e.g., setupTimeRecords() in one flavor, the in-kiosk code in the other flavor)

  • Have your main source set use that class and call that function

Gradle will pull in the implementation of the class from the flavor's source set for whatever build variant you are building, and that is the implementation that the main code will use in that build.

Upvotes: 3

Related Questions