0

Проблема с раздуванием элементов в приложении, вылетает следующее исключение: картинка и с исключением Вопрос что я делаю не так? Адаптер с ViewHolder

  private inner class IconsAdapter(var icons: List<AppIcon>) :
    RecyclerView.Adapter<IconsAdapter.IconHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IconsAdapter.IconHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
        return IconHolder(view)
    }

    override fun getItemCount(): Int = icons.size

    override fun onBindViewHolder(iconHolder: IconsAdapter.IconHolder, position: Int) {
        iconHolder.bind(icons[position])
    }

    private inner class IconHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {


        lateinit internal var imageView: ImageView
        lateinit internal var textView: TextView

        fun bind(appIcon: AppIcon) {
            imageView = itemView.findViewById(R.id.icon_id)
            textView = itemView.findViewById(R.id.name_id)

            imageView.setImageDrawable(appIcon.icon)
            textView.text = appIcon.label
            imageView.setOnClickListener(this)
        }

        override fun onClick(view: View?) {
            mCallBackClickListener!!.onButtonPressed(view, adapterPosition)
        }

    }

}

Элемент для Recycler View

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/icon_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_foreground"
        app:layout_constraintBottom_toTopOf="@id/name_id"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/name_id"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="@id/icon_id"
        app:layout_constraintRight_toRightOf="@id/icon_id"
        app:layout_constraintTop_toBottomOf="@id/icon_id" />

</android.support.constraint.ConstraintLayout>

Код фрагмента

class ShowAllAppFragment : Fragment() {


private lateinit var recyclerView: RecyclerView
private lateinit var appIcons: List<AppIcon>
private var mCallBackClickListener: OnShowAppFragmentListener? = null

init {
    Log.i(
        KeysCommonInteractor.KeysField.LOG_TAG,
        "Identificator of class is $this"
    )
}

companion object FragmentsFactory {

    internal val KEY_LIST = javaClass.canonicalName + "Names of applications"

    fun newInstance(listOfApps: List<AppIcon>): ShowAllAppFragment {
        val showAllAppFragment = ShowAllAppFragment()
        val arguments = Bundle()
        Log.i(
            KeysCommonInteractor.KeysField.LOG_TAG,
            "${javaClass.canonicalName} :  newInstance list = $listOfApps"
        )
        arguments.putParcelableArrayList(KEY_LIST, listOfApps as ArrayList<AppIcon>)
        showAllAppFragment.setArguments(arguments)
        return showAllAppFragment
    }
}


override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    var view = inflater.inflate(R.layout.show_all_app, container, false)

    recyclerView = view!!.findViewById(R.id.recycler_view)
    recyclerView.layoutManager = GridLayoutManager(context, 4)
    //  recyclerView.layoutManager = LinearLayoutManager(context)
    updateUI()
    return view
}

private fun updateUI() {

    appIcons = arguments!!.getParcelableArrayList(KEY_LIST)
    Log.d(
        KeysCommonInteractor.KeysField.LOG_TAG,
        "Count of apps in data ${appIcons.size}"
    )
    recyclerView.adapter = IconsAdapter(icons = appIcons)
}

private inner class IconsAdapter(var icons: List<AppIcon>) :
    RecyclerView.Adapter<IconsAdapter.IconHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IconsAdapter.IconHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
        return IconHolder(view)
    }

    override fun getItemCount(): Int = icons.size

    override fun onBindViewHolder(iconHolder: IconsAdapter.IconHolder, position: Int) {
        iconHolder.bind(icons[position])
    }

    private inner class IconHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {


        lateinit internal var imageView: ImageView
        lateinit internal var textView: TextView

        fun bind(appIcon: AppIcon) {
            imageView = itemView.findViewById(R.id.icon_id)
            textView = itemView.findViewById(R.id.name_id)

            imageView.setImageDrawable(appIcon.icon)
            textView.text = appIcon.label
            imageView.setOnClickListener(this)
        }

        override fun onClick(view: View?) {
            mCallBackClickListener!!.onButtonPressed(view, adapterPosition)
        }

    }

}

override fun onAttach(context: Context?) {
    super.onAttach(context)
    try {
        mCallBackClickListener = context as OnShowAppFragmentListener?
    } catch (e: ClassCastException) {
        throw ClassCastException(context!!.toString() + " must implement mShowAllAppFragmentListener")
    }

}


interface OnShowAppFragmentListener {
    fun onButtonPressed(view: View?, position: Int)
}

}

4
  • Проблема где-то тут override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IconsAdapter.IconHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, true) return IconHolder(view) } 11 ноя 2018 в 12:46
  • возможно у вас в ImageView стоит картинка недопустимо большого размера
    – Jarvis_J
    11 ноя 2018 в 15:23
  • Возможно, главный view у ViewHolder'а должен иметь ширину=match_parent
    – Yellastro
    11 ноя 2018 в 19:25
  • Так ничего не нашёл 11 ноя 2018 в 20:43

1 ответ 1

3

У Вас проблема конкретно в ImageView , если быть точнее то вы пытаетесь передать в него векторную картинку через старые атрубит android:src="@drawable/ic_launcher_foreground"

По этому у вас собственно и краш. Векторы передавать в ImageView нужно через новый атрибут

app:srcCompat="@drawable/ic_launcher_foreground"

так же в gradle вашего проекта добавьте в секцию defaultConfig поддержку векторов

 defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }

Кроме того ic_launcher_foreground лежит в ресурсах для api 24+ то есть так же обратите внимание на тот девайс с которого запускаете. а если быть еще проще, скормите ей обычную пнг.

1
  • Получаю иконки следующим образом: val availableActivities = packageManager.queryIntentActivities(intent, 0) apps = ArrayList() Log.i( KeysCommonInteractor.KeysField.LOG_TAG, "Count of runnable apps is ${availableActivities.size}" ) availableActivities.forEach { val appIcon = AppIcon( it.loadLabel(packageManager), it.activityInfo.name, it.activityInfo.loadIcon(packageManager) ) apps.add(appIcon) 12 ноя 2018 в 7:04

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.