JohnWick
JohnWick

Reputation: 31

Array position using onItemClickListener

I'm trying to get the position of an array using the onItemClickListner.

With the following code, I am able to pass the text of the item clicked but not the position of the array eg 0, 1, 2 etc.

       String[] menuItems = new String[]{"Hello", "Is it me", "Youre", "Looking for"};

    ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.menulists, R.id.menulistsTextView1, menuItems);
    ListView listView = (ListView) findViewById(R.id.mainListView1);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> l, View v, int position, long id) {

            String selected = (String) l.getItemAtPosition(position);


        }

Any tips on whether it is possible to do that, I tried changing String to int and also to use the getItemIDAtPosition function but would not work, would just close the application.

Cheers

EDIT

I have just taken a different approach to achieving what I want to do using if statements for the string of the item clicked. Thanks for the input

Upvotes: 0

Views: 78

Answers (3)

Maciej Sikora
Maciej Sikora

Reputation: 20162

As I understand Your problem - You want to get item on clicked position. Do do so use getItem(position) method of adapter. Code:

   String[] menuItems = new String[]{"Hello", "Is it me", "Youre", "Looking for"};

   //VERY IMPORTANT
   //adapter must be declared final to use it in onItemClick
   //or adapter should be object parameter
   final ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.menulists, R.id.menulistsTextView1, menuItems);

   ListView listView = (ListView) findViewById(R.id.mainListView1);
   listView.setAdapter(adapter);

   listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

     @Override
     public void onItemClick(AdapterView<?> l, View v, int position, long id) {

        String selected = <String>adapter.getItem(position);


     }

   });

Upvotes: 0

user273320
user273320

Reputation: 16

you may try this :

String itemClicked = menuItems[position];

Upvotes: 0

SANAT
SANAT

Reputation: 9277

You can get the position from method signature :

public void onItemClick(AdapterView<?> l, View v, int position, long id)

position give you index of selected item.

Upvotes: 3

Related Questions