我无法让 onItemClickListener 在我的代码中工作。为了测试它,如果单击其中一个视图(封面流中的图像),我在 onClick 中放置了一个 Toast 以在屏幕上显示一些文本,但没有结果。我可能做错了什么。我该怎么办?
下面显示的代码有两部分。第一部分来自我用来实现coverflow活动的coverFlowExample.java类文件,下面的第二部分代码来自另一个名为抽象类CoverAdapterView的类文件,它具有OnItemClickListener的抽象方法。
下面的代码在coverflowactivity 活动的oncreate 方法中。
我必须创建“int = xu 位置”,因为编译器不允许我直接使用 int 位置变量,该变量是 onItemClick 方法中采用的参数的一部分
// inner class inside of onCreate method for implememting OnIteimClickListener
class ClickOnImage implements OnItemClickListener {
@Override
public void onItemClick(CoverAdapterView<?> parent, View view,
int position, long id) {
int xu = position;
Toast.makeText(CoverFlowExample.this, "clicked on one of the images " + xu, Toast.LENGTH_SHORT).show();
}
}
接下来是与另一个类文件中的 OnItemClickListener 相关的代码
public abstract class CoverAdapterView<T extends Adapter> extends ViewGroup {
// inside this abstract class the below code is refers to the OnItemClickListener
/**
* The listener that receives notifications when an item is clicked.
*/
OnItemClickListener mOnItemClickListener;
/**
* Interface definition for a callback to be invoked when an item in this
* AdapterView has been clicked.
*/
public interface 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.
*/
void onItemClick(CoverAdapterView<?> parent, View view, int position, long id);
}
/**
* Register a callback to be invoked when an item in this AdapterView has
* been clicked.
*
* @param listener The callback that will be invoked.
*/
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
}
/**
* @return The callback to be invoked with an item in this AdapterView has
* been clicked, or null id no callback has been set.
*/
public final OnItemClickListener getOnItemClickListener() {
return mOnItemClickListener;
}
/**
* Call the OnItemClickListener, if it is defined.
*
* @param view The view within the AdapterView that was clicked.
* @param position The position of the view in the adapter.
* @param id The row id of the item that was clicked.
* @return True if there was an assigned OnItemClickListener that was
* called, false otherwise is returned.
*/
public boolean performItemClick(View view, int position, long id) {
if (mOnItemClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mOnItemClickListener.onItemClick(this, view, position, id);
return true;
}
return false;
}