setOnItemClickListener just take me the value of the first item in the list in android

2

Hi, I would like you to take a look at my code, the list of the filling from a call in the database where I dump the values in that list. What I want to do is that when you click on an item in the list, the data is displayed on an alert dialog. just take me the first item on the list even if you click on others

 lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                TextView tx1=adapterView.findViewById(R.id.txt1);
                TextView tx2=adapterView.findViewById(R.id.txt2);

                String texto1=tx1.getText().toString();
                String texto2=tx2.getText().toString();

                Toast.makeText(getApplicationContext(), texto1+" "+texto2, Toast.LENGTH_SHORT).show();
               
            }
        });
    
asked by adrian ruiz picazo 22.05.2018 в 17:48
source

2 answers

1

The View that comes to you as 2nd parameter is the row "clicked" on the list, so you must do findViewById on that to get the text of that row .

lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                TextView tx1=view.findViewById(R.id.txt1);
                TextView tx2=view.findViewById(R.id.txt2);

                String texto1=tx1.getText().toString();
                String texto2=tx2.getText().toString();

                Toast.makeText(getApplicationContext(), texto1+" "+texto2, Toast.LENGTH_SHORT).show();

            }
        });

More information:

About the parameters:

  

parent AdapterView : The AdapterView where the click event happened

     

view View : The view within AdapterView that was clicked (In your case Row)

     

position int : The position of the view on the adapter.

     

id long : the Id of the row of the item where it was clicked.

    
answered by 22.05.2018 / 17:57
source
0

The ListView sends you a int i parameter that can be translated as a position in the list. So what you could try is also:

lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

               Object item = list.getItemAtPosition(i); 

            }
        });

The above code should capture the data in the list in that position, and use it in your TextView or as appropriate.

    
answered by 22.05.2018 в 18:11