Sobes.tech
Middle

How do you ensure the accessibility of objects from a parent component in an Activity?

sobes.tech AI

Answer from AI

In Android, the accessibility of objects from a parent component (such as a fragment or view) in an Activity is provided through references to these objects, passed or obtained in various ways.

Main methods:

  • Direct reference retrieval through Activity methods:
    • findViewById() for views.
    • findFragmentById() or findFragmentByTag() for fragments.
    • References to managers (e.g., getSupportFragmentManager(), getSystemService()).
  • Passing references during creation: The parent object can pass a reference to itself or its child components during their creation (e.g., via constructor, factory method, or arguments).
  • Callback interfaces (Listener pattern): The child component calls methods of a predefined interface, which the Activity implements. The Activity subscribes to these calls.
  • Data Binding: Allows binding data and view logic with the Activity/fragment, providing access to layout elements.
  • ViewModel (architectural component): ViewModel can contain data or references accessible both to the Activity and its associated components.

Example with findViewById():

// In Activity
class MyActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my)

        val myView = findViewById<TextView>(R.id.myTextView) // Getting a reference to a view in Activity
        myView.text = "Accessible from Activity"
    }
}

Example with Callback interface:

// Interface for interaction
interface MyCallbacks {
    fun onSomethingHappen(data: String)
}

// Fragment that calls back
class MyFragment : Fragment() {
    private var callbacks: MyCallbacks? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is MyCallbacks) {
            callbacks = context // Activity implements the interface and becomes callback
        }
    }

    fun doSomething() {
        val result = "Some data from fragment"
        callbacks?.onSomethingHappen(result) // Calling Activity method
    }
}

// Activity implementing the interface
class MyActivity : AppCompatActivity(), MyCallbacks {
    override fun onSomethingHappen(data: String) {
        // Data received from fragment
        Log.d("MyActivity", "Data received from fragment: $data")
    }
}