How do I call the onItemClick method from inside another class?

248 Views Asked by At

[Background info: I'm a newbie learning to make a "to do list" app in Android Studio. Basically I have a dialog box pop-up when the user clicks on any item in the To Do list, which gives the user a choice of two buttons to 'Delete or Cancel' for any specific item that they click. Then I want that delete button to carry out the code in this method.]

I'm trying to call this onItemClick method (which I made in the MainActivity) from inside a dialog fragment class I created. I don't know what these parameter values are (it seems they are automatically generated) but Android Studio is asking me to pass the four parameters in when I want to call that onItemClick method for the Delete button. This is the method I'm trying to call:

'''

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    items.remove(position);
    adapter.notifyDataSetChanged();
    FileHelper.writeData(items, this); }

'''

I defined this method in the MainActivity because all the stuff inside it was created and defined in that activity already (adapterview, items). FileHelper is another class I made.

1

There are 1 best solutions below

0
chef417 On

I'm assuming you're using the list. You can check more info for each of the arguments in the documentation (see the bottom of the page).

  • If this is a click listener for your list, where AdapterView<?> parent is the parent view of the object that you've clicked - if using ListView, this object would be that ListView.
  • View view is the actual view that you've clicked. E.g. if you have a list of TextViews and you click on one of them, here you'll get that text view.
  • int position is the position of the clicked item in your list (0 being the first item).
  • long id is the id of the clicked item, you usually control that in the adapter.

So if you want to retrieve the clicked element for example, you can use getItemAtPosition(position) on your list view to fetch the actual item object.