How to access the setOnItemClickListener () method of a ListView Kotlin?

0

I am new to the development on android and I am trying to make a small application and I run into the following problem, I hope you can help me:

I am working on a Drawer Menu so in my events nav_XXXX I do some PHP queries

For example if I click on nav_IniciarRuta command to execute a query that sends me some data from the server. When I receive them I convert them into a list and put them in the variable datList, then I adapt the ListView that I have the xml.

Each nav, gives me different information, but in the end it ends up in the ListView.

Now, my problem is that I can not access the setOnItemClickListener () function from my list from anywhere because my variable is inaccessible. OK, I can not use my list.

Any suggestions?

    
asked by Oscar Byron 09.06.2018 в 00:44
source

1 answer

0

This is the declaration of your ListView in the layout

   <ListView
        android:id="@+id/ListaMAIN"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    >
   </ListView>

To access the setOnItemClickListener() method you must first obtain its reference, this must be done whether you use Java or Kotlin , which is done this way:

  //Obtiene referencia.
  var miLista = findViewById<ListView>(R.id.ListaMAIN) as ListView
  //Asigna listener.
  miLista.setOnItemClickListener(AdapterView.OnItemClickListener { parent, view, position, id ->

            //Realiza alguna acción!

        })

Assign OnItemClickListener to ListView in Kotlin.

This is an example:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Obtiene referencia de ListView.
        var miLista = findViewById<ListView>(R.id.ListaMAIN) as ListView

       //Valores a agregar en ListView
        val values = arrayOf(
            "Panama",
            "Costa Rica",
            "Rumania",
            "México",
            "España",
            "Peru",
            "Ecuador",
            "Argentina")

        //Agrega valores a adapter.
        val adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values)
        //Asigna Adapter a ListView
        miLista.adapter =adapter


        miLista.setOnItemClickListener(AdapterView.OnItemClickListener { parent, view, position, id ->

            Toast.makeText(this@MainActivity, "You clicked my List.", Toast.LENGTH_SHORT).show()

        })

}

    
answered by 04.09.2018 в 18:03