我有麻烦完全理解上下文如何在ANdroid工作室(Kotlin)工作



在阅读完文档和Stackoverflow的答案后,我很难理解Android Studio中的上下文。根据我的理解,Context给出了当前应用程序/对象的上下文。(我需要帮助的行用*****表示)

当使用val context = holder.view.context时,我是否从我各自的XML视图中获得上下文?

如果是这样的话,为什么有必要将上下文输入到意图对象val intent = Intent(context, DetailActivity::class.java)中呢?

我不能只用this代替吗?如果有人能告诉我上下文是如何用例子工作的,我会很感激的,谢谢!

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)
}
}

当使用val context = holder.view.context时,我正在获取context从我各自的XML视图?

这里的上下文是Activity,你可以从Activity

的视图中获得Activity的上下文

如果是这种情况,为什么有必要将该上下文输入意图对象val意图=意图(context)DetailActivity: class.java) ?

在这个例子中,Intent对象期望第一个参数是Context类型。更多信息见Intent

我不能用这个代替吗?

。因为RecyclerView。适配器不是Context或Context的子类

最新更新