简体   繁体   English

如何从另一个 class 内部调用 onItemClick 方法?

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

[Background info: I'm a newbie learning to make a "to do list" app in Android Studio. [背景信息:我是一名新手,正在学习在 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.我试图从我创建的对话框片段 class 中调用这个 onItemClick 方法(我在 MainActivity 中创建的)。 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.我不知道这些参数值是什么(似乎它们是自动生成的),但是当我想为删除按钮调用 onItemClick 方法时,Android Studio 要求我传递四个参数。 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).我在 MainActivity 中定义了这个方法,因为它里面的所有东西都是在那个 Activity 中创建和定义的(adapterview,items)。 FileHelper is another class I made. FileHelper 是我制作的另一个 class。

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).您可以在文档中查看每个 arguments 的更多信息(参见页面底部)。

  • 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 .如果这是您列表的单击侦听器,其中AdapterView<?> parent是您单击的 object 的父视图 - 如果使用ListView ,则此 object 将是该ListView
  • View view is the actual view that you've clicked. View view是您单击的实际视图。 Eg if you have a list of TextView s and you click on one of them, here you'll get that text view.例如,如果您有一个TextView列表,然后单击其中一个,您将在此处获得该文本视图。
  • int position is the position of the clicked item in your list (0 being the first item). int position是列表中单击项目的 position(0 是第一项)。
  • long id is the id of the clicked item, you usually control that in the adapter. long id是被点击项的 id,你通常在适配器中控制它。

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.因此,例如,如果您想检索被点击的元素,您可以在列表视图中使用getItemAtPosition(position)来获取实际项目 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM