从 Adapter 中的 Resources 获取一个字符串

Get a string from Rescources in Adapter

正在尝试从 R.string 获取字符串值以显示在我的适配器中,但在 return 中仅获取一个整数:

class AlarmListAdapter() :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {

class MyViewHolder(binding: LayoutAlarmBinding) : RecyclerView.ViewHolder(binding.root)

var alarmList = ArrayList<Alarm>()


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    val binding = LayoutAlarmBinding.inflate(LayoutInflater.from(parent.context))
    return MyViewHolder(binding)
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    val currentItem = alarmList[position]
    val recurring = currentItem.repeat


    //set repeat text
    holder.itemView.findViewById<TextView>(R.id.tv_repeat_days).text =
        if (recurring) {
            "${R.string.daily_alarm.}"
        } else {
            "${R.string.once_alarm}"
        }

我也试过这样设置值:

val once : String? =  Resources.getSystem().getString(R.string.once_alarm) ?: "Once"

但在这种情况下得到:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pleavinseven.alarmclockproject, PID: 16832
android.content.res.Resources$NotFoundException: String resource ID #0x7f1200d0

是否有办法解决这个问题,或者我是否需要以某种方式将此功能从适配器中移出?

View 获取上下文并调用 getString:

holder.itemView.context.getString(R.string.here)

在您的情况下,您的代码将如下所示:

//set repeat text
holder.itemView.findViewById<TextView>(R.id.tv_repeat_days).text =
     if (recurring) 
         holder.itemView.context.getString(R.string.daily_alarm)
     else 
         holder.itemView.context.getString(R.string.once_alarm)

另一个解决方案是将 Context 作为参数传递给 AlarmListAdapter:

class AlarmListAdapter(val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
....
//set repeat text
holder.itemView.findViewById<TextView>(R.id.tv_repeat_days).text =
     if (recurring) 
         context.getString(R.string.daily_alarm)
     else 
         context.getString(R.string.once_alarm)
}