Как я могу получить доступ к строкам в `strings.xml` из класса адаптера Recycler, используя` getString () `в Kotlin - PullRequest
1 голос
/ 28 января 2020

Мне нужен доступ к строкам в strings.xml из пользовательского класса Recycler Adapter, но я получаю сообщение об ошибке, как описано. Вот мой класс Kotlin Recycler Adapter с методом onBindViewHolder(), где я пытаюсь получить доступ к строкам с заполнителями miles и poundSign:

import android.content.res.Resources
import android.provider.Settings.Global.getString
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.text.DecimalFormat

class SiteAdapter(
    private val mainActivity: CountiesActivity,
    private val siteList: List<Site>) : RecyclerView.Adapter<SiteAdapter.ListItemHolder>() {

    inner class ListItemHolder(view: View):
        RecyclerView.ViewHolder(view),
        View.OnClickListener {

        internal var name = view.findViewById<View>(R.id.textViewSiteName) as TextView

        internal var distance = view.findViewById<View>(R.id.textViewSiteDistance) as TextView

        internal var price = view.findViewById<View>(R.id.textViewSitePrice) as TextView

        init {

            view.isClickable = true
            view.setOnClickListener(this)

        }

        override fun onClick(view: View) {

            mainActivity.showDetails(adapterPosition)

        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListItemHolder {

        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.recycler_list_item, parent, false)

        return ListItemHolder(itemView)

    }

    override fun getItemCount(): Int {

        if (siteList != null) {
            return siteList.size
        }
        // error
        return -1

    }

    override fun onBindViewHolder(holder: ListItemHolder, position: Int) {

        val site = siteList[position]

        holder.name.text = site.name
        holder.distance.text = site.distance.toString() + Resources.getSystem().getString(R.string.miles)
        val decimalFormatter = DecimalFormat("#,###.00")
        holder.price.text = Resources.getSystem().getString(R.string.poundSign) + decimalFormatter.format(site.price).toString()

    }


}

Вот мой файл strings.xml:

<resources>
    <string name="app_name">GoSiteUK</string>
    <string name="title_england">England</string>
    <string name="title_scotland">Scotland</string>
    <string name="title_wales">Wales</string>
    <string name="title_nireland">N.Ireland</string>
    <string name="helpInstructions">\n\n\n\n\n\nSelect from the available countries at the bottom of the screen to display a list of
        counties for that country. Then select a county for which you wish to see campsites, caravan sites or motorhome sites. Select
    a particular site that you wish to travel to and you will be presented with more information about the site. Click on \"Take Me
    Here\" and a map will be displayed with navigation instructions and route information to follow to take you to that selected
    site.\n\nFor support contact:\n\nriverstonetechuk@gmail.com\n</string>
    <string name="help">Help</string>
    <string name="title_counties">--- Counties ---</string>
    <string name="title_regions">--- Regions ---</string>
    <string name="title_areas">--- Areas ---</string>
    <string name="title_districts">--- Districts ---</string>

    <string name="name">Name:</string>
    <string name="distance">Distance:</string>
    <string name="price">Price:</string>
    <string name="miles"> miles</string>
    <string name="poundSign">£</string>
</resources>

Сообщения об ошибках показаны ниже:

-01-28 16:09:25.229 16740-16740/com.riverstonetech.gositeuk W/ResourceType: No known package when getting value for resource number 0x7f0f0049
2020-01-28 16:09:25.230 16740-16740/com.riverstonetech.gositeuk D/AndroidRuntime: Shutting down VM
2020-01-28 16:09:25.231 16740-16740/com.riverstonetech.gositeuk E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.riverstonetech.gositeuk, PID: 16740
    android.content.res.Resources$NotFoundException: String resource ID #0x7f0f0049
        at android.content.res.Resources.getText(Resources.java:335)
        at android.content.res.Resources.getString(Resources.java:381)

Любые решения для решения этой проблемы приветствуются.

Ответы [ 2 ]

1 голос
/ 28 января 2020

Вы пытаетесь получить доступ к файлу String системы Android, а не к вашей String. xml вашего приложения!

Фактически, если вы хотите получить доступ к известному значению ресурса Android, вы должны использовать его следующим образом: Resources.getSystem().getString(android.R.string.cancel)

В противном случае, если вы хотите получить доступ к собственному файлу ресурса String, вы должен вызвать функцию getResources() из контекста. Например: context.getResources().getString(R.string.poundSign);

Если CountiesActivity является Activity, вы можете позвонить mainActivity.getResources().getString(R.string.whatever);

Поскольку сборщик мусора может иногда разрушать вашу деятельность, хороший способ хранения контекст действия должен хранить WeakReferences этого. Это предотвращает наличие l oop ссылок на ваше контекстное приложение и утечку памяти. Взгляните на документацию .

Я надеюсь, что это поможет, и не стесняйтесь задавать вопросы, если они не ясны. Веселитесь!

1 голос
/ 28 января 2020

Я предполагаю, что проблема в причине доступа

Resources.getSystem()

. Я настоятельно рекомендую этого не делать.

Предложение со своей стороны: Сделать представление в ListItemHolder как доступное поле, подобное этому

inner class ListItemHolder(val view: View)

И затем вы можете получить доступ к строковым ресурсам через это представление:

holder.price.text = holder.view.context.getString(R.string.poundSign) + decimalFormatter.format(site.price).toString()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...