这是android应用程序项目的一部分,我有这段代码,我无法理解setOnItemClickListener将(AdapterView.OnItemClickListener监听器)作为参数,但其他方法void onItemClick也在参数空间中。我无法理解AdapterView.OnItemClickListener()的对象如何调用/使用onItemClick?

  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            String forecast = mForecastAdapter.getItem(position);
            Intent intent = new Intent(getActivity(), MainActivity2Activity.class)
                    .putExtra(Intent.EXTRA_TEXT, forecast);
            startActivity(intent);
        }
    })

最佳答案

new AdapterView.OnItemClickListener() {...}anonymous class的示例。这只是手动实现AdapterView.OnItemClickListener interface并手动覆盖onItemClick方法(它是abstract method),然后实例化并将其引用传递到setOnItemClickListener方法中的快捷方式。在不使用匿名类的情况下,代码如下所示:

class MyOnItemClickListener implements AdapterView.OnItemClickListener{

    /**
     * Callback method to be invoked when an item in this AdapterView has
     * been clicked.
     * <p/>
     * Implementers can call getItemAtPosition(position) if they need
     * to access the data associated with the selected item.
     *
     * @param parent   The AdapterView where the click happened.
     * @param view     The view within the AdapterView that was clicked (this
     *                 will be a view provided by the adapter)
     * @param position The position of the view in the adapter.
     * @param id       The row id of the item that was clicked.
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //your code here
    }
}


然后实例化并将其分配给您的list view

MyOnItemClickListener clickListener = new MyOnItemClickListener();
listView.setOnItemClickListener(clickListener);

关于android - Android中的基本代码阅读,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31124467/

10-09 23:06