0

Pues intento generar una lista personalizada dentro de un fragmento en Android Studio (Kotlin) y me da un error en esta linea que no comprendo.

listView.adapter = MyCustomAdapter(this) <-- El "this" me da error.

Aclaro que lo he probado sobre el MainActivity y funciona perfecto, pero no quiero hacerlo alli ya que desde alli solo controlo mi toolbar y fragments.

class HomeFragment : Fragment() {

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    val root = inflater.inflate(R.layout.fragment_establecimientos, container, false)
    val textView: TextView = root.findViewById(R.id.text_home)
    textView.text = "Establecimientos cercanos"

    /* LISTVIEW*/
    val listView = root.findViewById<ListView>(R.id.listView)
    listView.adapter = MyCustomAdapter(this) /* <--- ERROR AQUI EN "this" */

    // Inflate the layout for this fragment
    return root

}


private class MyCustomAdapter(context: Context): BaseAdapter() {

    private val mContext: Context

    private val names = arrayListOf<String>(
        "Donald Trump", "Steve Jobs", "Tim Cook", "Mark Zuckerberg", "Barack Obama", "Antonio Ruiz"
    )

    private val descriptions = arrayListOf<String>(
        "Descripcion 1", "Desc 2", "Desc 6", "Otra descripcion", "Nueva Desc", "Descripción con tilde"
    )

    init {
        mContext = context
    }

    // how many rows in my list
    override fun getCount(): Int {
        return names.size
    }

    // ignore
    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    // ignore
    override fun getItem(position: Int): Any {
        return ""
    }

    // responsible for rendering out each row
    override fun getView(position: Int, convertView: View?, viewGroup: ViewGroup?): View {
        val layoutInflater = LayoutInflater.from(mContext)
        val rowMain = layoutInflater.inflate(R.layout.row, viewGroup, false)

        val nameTextView = rowMain.findViewById<TextView>(R.id.textView1)
        nameTextView.text = names.get(position)

        val descriptionTextView = rowMain.findViewById<TextView>(R.id.textView2)
        descriptionTextView.text = descriptions.get(position)

        return rowMain
    }

}

}

2 respuestas 2

0

Ya he encontrado el error y esta es la solución.

Hay que cambiar esta línea:

listView.adapter = MyCustomAdapter(this)

por esta otra:

listView.adapter =
            getActivity()?.let { MyCustomAdapter(it) }
0

Ese "this" que pones al principio está haciendo referencia al Fragment, mientras que el Adapter necesita el context de la Activity en la cual se encuentra el Fragment. Hay un método, a partir de la librerua 27.1.0 para recoger el contexto, que sería requireContext().

https://developer.android.com/reference/androidx/fragment/app/Fragment#requireContext()

La línea quedaría así:

listView.adapter = MyCustomAdapter(requireContext())

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.