Home > Mobile >  I am having troubles fully understanding how Context works in ANdroid Studio(Kotlin)
I am having troubles fully understanding how Context works in ANdroid Studio(Kotlin)

Time:06-20

I am having difficulties understanding Context in Android Studio after reading through docs and answers from Stackoverflow. From what I understand Context gives the Context of the current application/object. (The lines which I need help with are denoted by *****)

When using val context = holder.view.context am I getting the Context from my respective XML views?

If that is the case why is it necessary to input that context into the intent object val intent = Intent(context, DetailActivity::class.java)?

Can't I just use this instead? I would appreciate if anybody could walk me through on how Context work with examples thanks!

class LetterAdapter :
RecyclerView.Adapter<LetterAdapter.LetterViewHolder>() {

// Generates a [CharRange] from 'A' to 'Z' and converts it to a list
private val list = ('A').rangeTo('Z').toList()

/**
 * Provides a reference for the views needed to display items in your list.
 */
class LetterViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
    val button = view.findViewById<Button>(R.id.button_item)
}

override fun getItemCount(): Int {
    return list.size
}

/**
 * Creates new views with R.layout.item_view as its template
 */
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LetterViewHolder {
    val layout = LayoutInflater
            .from(parent.context)
            .inflate(R.layout.item_view, parent, false)
    // Setup custom accessibility delegate to set the text read
    layout.accessibilityDelegate = Accessibility
    return LetterViewHolder(layout)
}

/**
 * Replaces the content of an existing view with new data
 */
override fun onBindViewHolder(holder: LetterViewHolder, position: Int) {
    val item = list.get(position)
    holder.button.text = item.toString()
    holder.button.setOnClickListener {
        val context = holder.view.context *****

        val intent = Intent(context, DetailActivity::class.java)*****

        intent.putExtra(DetailActivity.LETTER, holder.button.text.toString())



        context.startActivity(intent)
    }
}

CodePudding user response:

When using val context = holder.view.context am I getting the Context from my respective XML views?

here context would be the Activity, you can get the Activity context from the views of the Activity

If that is the case why is it necessary to input that context into the intent object val intent = Intent(context, DetailActivity::class.java)?

The Intent object expects the first parameter of type Context in this case. See Intent for more information

Can't I just use this instead?

No. Because RecyclerView.Adapter is not a Context or subclass of Context

  • Related