在context
适配器中使用SharedPreference
时应使用哪个RecyclerView
?这是令人困惑的,因为在默认设置中,context
中的val mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
显示为未解析的引用。
class MyRVAdapter(private val myString: ArrayList<String>): RecyclerView.Adapter<MyRVAdapter.MyViewHolder>() {
private val typeA = 1
private val typeB = 2
override fun onCreateViewHolder(parent: ViewGroup, type: Int): MyViewHolder {
return when (type) {
typeA -> MyViewHolder(inflateHelper(R.layout.rv_type_a, parent))
typeB -> MyViewHolder(inflateHelper(R.layout.rv_type_b, parent))
else -> MyViewHolder(inflateHelper(R.layout.rv_type_a, parent))
}
}
override fun onBindViewHolder(viewHolder: MyViewHolder, position: Int) {
if (getItemViewType(position) == typeA) {
// Check preference (what's the correct context?)
val mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
valueDestinationExpanded = mSharedPreferences.getBoolean("my_preference", true)
}
else if (getItemViewType(position) == typeB) {
}
}
private fun inflateHelper(resId: Int, parent: ViewGroup): View {
return LayoutInflater.from(parent.context).inflate(resId, parent, false)
}
override fun getItemViewType(position: Int): Int {
return if (position == 0) typeA
else typeB
}
}
任何Context
都可以。无法解析您的context
引用,因为您没有该名称的变量或属性,就像在View
或Activity
中一样。在onBindViewHolder
中获得一个最方便的方法是viewHolder.itemView.context
(或Java中的viewHolder.itemView.getContext()
)。