ListView ItemClickListener

A ListView can listen for item click events.

I followed a web tutorial to create the example below:
https://www.homeandlearn.co.uk/android/android_simple_list_items.html

You should start from previous tutorials so you can start out with a ListView, ArrayList, and ArrayAdapter working together to display some items on your device screen.

The example code below goes into the MainActivity’s onCreate() method, where a ListView named lv has already been created.

We are creating an OnItemClickListener from AdapterView class named listClick. A method is defined which opens a new activity, sending information about an object to that activity.

The listener doesn’t have to open a new activity, but this type of thing would allow you to open a new screen that edits that object or displays more information about it.

Notice that the code below has an override on the onItemClick() method. Change the code in this method to change what happens when an item in the ListView is clicked.

        AdapterView.OnItemClickListener listClick = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, ItemActivity.class);
                Robot r = robots.get(position);
                String name = r.getName();
                intent.putExtra("name", name);
                startActivity(intent);
            }
        };
        lv.setOnItemClickListener(listClick);

In order for this to work, you also need to create the other Activity (ItemActivity in this case).

ItemActivity’s onCreate() method needs to fetch the data that was sent as an extra from the other activity:

itemName = findViewById(R.id.itemName);
Intent intent = getIntent();
Bundle bd = intent.getExtras();
String rName = (String) bd.get("name");
itemName.setText(rName);

If you are using a custom adapter, you will need to add “focusable = false” for each one of your views in the item layout file.
You can do that by going into the “Text” tab of the layout instead of the “Design” view of the layout.
Then create a new line, type “focusable” and set it to false. This needs to be done for all of the views in the layout.

This is the line to add:

android:focusable="false"